Mybatis之动态sql

在mybatis中,它提供了一些动态sql标签,可以让程序员更快的进行mybatis的开发,这些动态sql可以通过sql的可重用性。。

常用的动态sql标签:if标签、where标签、sql片段、foreach标签

If标签/where标签

<select id="findByMap" parameterType="map" resultType="com.tf.domain.Users">
    select * from users
    <where> 
       <if test="name!=null and name!='' ">
       and name like #{name}
       </if>
       <if test="password!=null and password!='' ">
       and password=#{password}
       </if>
    </where>
    </select>

测试类

Map<String,Object> map = new HashMap<String,Object>();
    map.put("name", "coco");
    map.put("password", "admin");
   List<Users> list = usersMapper.findByMap(map);
for (Users users : list) {
	System.out.println(users);
}

Sql片段

Sql片段可以让代码有更高的可重用性

Sql片段需要先定义后使用

比如:上面的代码修改为

<!-- 抽取sql片断 -->
    <sql id="whereClass">
     <where> 
       <if test="name!=null and name!='' ">
       and name like #{name}
       </if>
       <if test="password!=null and password!='' ">
       and password=#{password}
       </if>
    </where>
    </sql>
    <select id="findByMap" parameterType="map" resultType="com.tf.domain.Users">
    select * from users
     <include refid="whereClass"></include>
    </select>

 foreach标签

可变参数 查询:SELECT * FROM users WHERE id IN (2,4,5)

 <select id="findByIds" parameterType="list" resultType="com.tf.domain.Users"> 
    select * from users where id in
    <foreach collection="list" item="id" open="(" close=")" separator=",">
      #{id}
    </foreach>
    </select>
    

测试类

List<Integer> ids= new ArrayList<Integer>();
   ids.add(2);
   ids.add(4);
   ids.add(5);
	 List<Users> ls =	usersMapper.findByIds(ids);
	 for (Users users : ls) {
		System.out.println(users);
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值