为什么使用动态SQL
在写SQL语句时,往往会有一些查询条件,但这些查询条件有时候有,有时候没有,那么mybatis提供的动态SQL可以解决这类问题。
如:根据条件查询用户列表,如果用户名不为空,则返回名字为参数的用户列表,如果为空则返回全部用户列表。
不过静态SQL也可以解决,但是写起来比较繁琐。
各有各的优缺点,待详细了解。
动态SQL之 if 标签
IUserDao接口,创建方法
/**
* 根据传入参数条件查询用户列表
* @param user 查询的条件:有可能有用户名,有可能有性别,也有可能有地址,还有可能是都有
* @return
*/
List<User> findUserByCondition(User user);
然后映射文件IUserDao.xml里配置该方法的sql语句
<select id="findUserByCondition" resultMap="userMap" parameterType="user">
select * from user where 1=1
<if test="userName != null"> test中为参数的成员变量
and username = #{userName}
</if>
<if test="userSex != null">
and sex = #{userSex}
</if>
</select>
流程跟if语句一样,要是用户名不为null,则在语句后面加and username = #{userName},反之不添加,直接执行下一个判断 或 结束。
注意:if标签的 test 属性中写的是对象的属性名,如果是包装类的对象要使用 OGNL 表达式的写法。除了sql语句的东西,其他都严格要求大小写区别。
这里的parameterType为什么不是全限定类名?
因为在SqlMapConfig.xml中配置了实体类User的别名。
为什么要用where 1=1
?
动态SQL之 where 标签
为了简化上面 where 1=1 的条件拼装,我们可以采用标签来简化开发,也为了看起来思路清晰一点,将需要判断的条件加where标签里面,方便区分。(效果跟上面的一样)
<!-- where 标签 -->
<select id="findUserByCondition" resultMap="userMap" parameterType="user">
select * from user
<where>
<if test="userName != null">
and username = #{userName}
</if>
<if test="userSex != null">
and sex = #{userSex}
</if>
</where>
</select>
测试方法:
动态SQL之foreach标签
有时候,我们写SQL语句会筛选用户ID是否在一个集合里面,如:select * from user where id in(…);
我们在mybatis可以使用foreach标签实现。
在IUserDao接口创建方法:
/**
* 根据queryVo中的id集合实现查询用户列表
* @param vo
* @return
*/
List<User> findUserInIds(QueryVo vo);
通过包装对象QueryVo 传入参数条件,所以在QueryVo 类中创建一个集合ids,并生成其的get、set方法。
然后就在IUserDao.xml中配置该方法
<select id="findUserInIds" resultMap="userMap" parameterType="com.itheima.domain.QueryVo">
select * from user
<where>
<if test="ids != null and ids.size()>0">
<foreach collection="ids" open="and id in(" close=")" item="uid" separator=",">
#{uid}
</foreach>
</if>
</where>
</select>
foreach标签用于遍历集合:
它的属性:
- collection:代表要遍历的集合元素,注意编写时不要写#{}
- open:代表语句的开始部分
- close:代表结束部分
- item:代表遍历集合的每个元素,生成的变量名
- sperator:代表分隔符
测试方法:
Mybatis 中简化编写的 SQL 片段
Sql 中可将重复的 sql 提取出来,使用时用 include 引用即可,最终达到 sql 重用的目的。
如:查看了这么多查询方法,都存在一句重复的:
select * from user
那么使用sql标签,将这句抽取出来
<!-- 了解的内容,抽取重复的sql语句,
注意:如果抽取语句后面还要加句子的话,分号; 不能加在抽取语句里面,否则报错 -->
<sql id="defaultUser">
select * from user
</sql>
然后在方法配置内引入就行,这时就可以使用include标签
举例:
findAll方法:
<select id="findAll" resultMap="userMap">
<!--引入被抽取的语句-->
<include refid="defaultUser"></include>
</select>
findUserInIds方法:
<select id="findUserInIds" resultMap="userMap" parameterType="com.itheima.domain.QueryVo">
<include refid="defaultUser"></include>
<where>
<if test="ids != null and ids.size()>0">
<foreach collection="ids" open="and id in(" close=")" item="uid" separator=",">
#{uid}
</foreach>
</if>
</where>
</select>