目录
9.4 Mybatis中简化编写的SQL片段 : 标签的使用
九、Mybatis 映射文件之动态SQL
9.1 <if> 标签的使用
<select id="findByCondition" parameterType="user" resultType="user">
select * from user where 1 = 1
<if test="username != null">
and username like #{username}
</if>
<if test="sex != null">
and sex = #{sex}
</if>
</select>
<if>标签的test属性中写的是对象的属性名,如果是包装类的对象要使用OGNL表达式的写法,另外要注意where 1=1 的作用。
9.2 <where> 标签的使用
<select id="findByCondition" parameterType="user" resultType="user">
select * from user
<where>
<if test="username != null">
and username like #{username}
</if>
<if test="sex != null">
and sex = #{sex}
</if>
</where>
</select>
注意:<where >可以自动处理第一个and
9.3 <foreach> 标签的使用
这里我们先创建一个QueryVo类来封装一个List集合:
QueryVo.java
package com.cpz.domain;
import java.util.ArrayList;
import java.util.List;
public class QueryVo {
private User user;
private List<Integer> ids = new ArrayList<Integer>();
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
}
UserDao.xml
<!--4.3 动态SQL标签之<foreach>标签
collection:使用ognl读取queryVo实体中的集合属性名
open:sql语句的前缀
close:sql语句的后缀
item:遍历集合的每个值的标识
separator:遍历集合的每个值的分隔符
-->
<select id="findByCondition2" resultType="user" parameterType="queryVo">
select * from user
<where>
<if test="ids != null and ids.size() > 0">
<foreach collection="ids" open=" and id in (" close=")" item="id" separator=",">
#{id}
</foreach>
</if>
</where>
</select>
TestUser.java
public void findByCondition2(){
List<Integer> ids = new ArrayList<Integer>();
ids.add(41);
ids.add(42);
ids.add(43);
QueryVo queryVo = new QueryVo();
queryVo.setIds(ids);
List<User> list = userDao.findByCondition2(queryVo);
for (User user : list) {
System.out.println(user);
}
}
9.4 Mybatis中简化编写的SQL片段 :<sql> 标签的使用
可以将sql语句中重复的部分提取出来,类似于:select * from user,使用时用include进行引用即可
<sql id="defaultSql">
select * from user
</sql>
<select id="findByCondition" parameterType="user" resultType="user">
<include refid="defaultSql"></include>
<where>
<if test="username != null">
and username like #{username}
</if>
<if test="sex != null">
and sex = #{sex}
</if>
</where>
</select>