在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);
}