MyBatis从入门到精通(七):MyBatis动态Sql之choose,where,set标签的用法
最近在读刘增辉老师所著的《mybatis从入门到精通》一书,很有收获,于是将自己学习的过程以博客形式输出,如有错误,欢迎指正,如帮助到你,不胜荣幸!
本篇博客主要讲解如何使用choose,where,set标签生成动态的sql。
1. choose 用法
假设有这样1个需求:当参数id有值时优先使用id查询,当id没有值时就去判断用户名是否有值,如果有值就用用户名查询,如果没值,就使查询无结果。
首先,我们在接口sysusermapper中添加如下方法:
/** * 根据用户id或用户名查询 * * @param sysuser * @return */ sysuser selectbyidorusername(sysuser sysuser);
然后在对应的sysusermapper.xml中添加如下代码:
<select id="selectbyidorusername" resulttype="com.zwwhnly.mybatisaction.model.sysuser"> select id, user_name, user_password, user_email, create_time from sys_user where 1 = 1 <choose> <when test="id != null"> and id = #{id} </when> <when test="username != null and username != ''"> and user_name = #{username} </when> <otherwise> and 1 = 2 </otherwise> </choose> </select>
注意事项:
在以上的代码中,如果没有otherwise这个限制条件,当id和username都为null时,所有的用户都会被查询出来,但我们接口的返回值是sysuser,当查询结果是多个时就会报错。添加otherwise条件后,由于where条件不满足,因此在这种情况下就查询不到结果。
最后,在sysusermappertest测试类中添加如下测试方法:
@test public void testselectbyidorusername() { sqlsession sqlsession = getsqlsession(); try { sysusermapper sysusermapper = sqlsession.getmapper(sysusermapper.class); // 按id查询 sysuser query = new sysuser(); query.setid(1l); query.setusername("admin"); sysuser sysuser = sysusermapper.selectbyidorusername(query); assert.assertnotnull(sysuser); // 只按username查询 query.setid(null); sysuser = sysusermapper.selectbyidorusername(query); assert.assertnotnull(sysuser); // id 和 username 都为空 query.setusername(null); sysuser = sysusermapper.selectbyidorusername(query); assert.assertnull(sysuser); } finally { sqlsession.close(); } }
运行测试代码,测试通过,输出日志如下:
debug [main] - ==> preparing: select id, user_name, user_password, user_email, create_time from sys_user where 1 = 1 and id = ?
debug [main] - ==> parameters: 1(long)
trace [main] - <== columns: id, user_name, user_password, user_email, create_time
trace [main] - <== row: 1, admin, 123456, admin@mybatis.tk, 2019-06-27 18:21:07.0
debug [main] - <== total: 1
debug [main] - ==> preparing: select id, user_name, user_password, user_email, create_time from sys_user where 1 = 1 and user_name = ?
debug [main] - ==> parameters: admin(string)
trace [main] - <== columns: id, user_name, user_password, user_email, create_time
trace [main] - <== row: 1, admin, 123456, admin@mybatis.tk, 2019-06-27 18:21:07.0
debug [main] - <== total: 1
debug [main] - ==> preparing: select id, user_name, user_password, user_email, create_time from sys_user where 1 = 1 and 1 = 2
debug [main] - ==> parameters:
debug [main] - <== total: 0
2. where 用法
where标签的作用:如果该标签包含的元素中有返回值,就插入一个where,如果where后面的字符串是以and或者or开头的,就将它们剔除。
假设有这样1个需求:根据用户的输入条件来查询用户列表,如果输入了用户名,就根据用户名模糊查询,如果输入了邮箱,就根据邮箱精确查询,如果同时输入了用户名和邮箱,就用这两个条件去匹配用户。
首先,我们在接口sysusermapper中添加如下方法:
/** * 根据动态条件查询用户信息(使用where标签) * * @param sysuser * @return */ list<sysuser> selectbyuserwhere(sysuser sysuser);
然后在对应的sysusermapper.xml中添加如下代码:
<select id="selectbyuserwhere" resulttype="com.zwwhnly.mybatisaction.model.sysuser"> select id, user_name, user_password, user_email, create_time from sys_user <where> <if test="username != null and username != ''"> and user_name like concat('%',#{username},'%') </if> <if test="useremail != null and useremail != ''"> and user_email = #{useremail} </if> </where> </select>
当if条件都不满足的时候,where元素中没有内容,此时的sql语句不会有where,语法正确。
如果if条件满足,where元素的内容就是以and开头的条件,where会自动去掉开头的and,保证sql语句的正确。
最后,在sysusermappertest测试类中添加如下测试方法:
@test public void testselectbyuserwhere() { sqlsession sqlsession = getsqlsession(); try { sysusermapper sysusermapper = sqlsession.getmapper(sysusermapper.class); // 只按用户名查询 sysuser query = new sysuser(); query.setusername("ad"); list<sysuser> sysuserlist = sysusermapper.selectbyuserwhere(query); assert.asserttrue(sysuserlist.size() > 0); // 只按邮箱查询 query = new sysuser(); query.setuseremail("test@mybatis.tk"); sysuserlist = sysusermapper.selectbyuserwhere(query); assert.asserttrue(sysuserlist.size() > 0); // 同时按用户民和邮箱查询 query = new sysuser(); query.setusername("ad"); query.setuseremail("test@mybatis.tk"); sysuserlist = sysusermapper.selectbyuserwhere(query); // 由于没有同时符合这两个条件的用户,因此查询结果数为0 assert.asserttrue(sysuserlist.size() == 0); } finally { sqlsession.close(); } }
运行测试代码,测试通过,输出日志如下:
debug [main] - ==> preparing: select id, user_name, user_password, user_email, create_time from sys_user where user_name like concat('%',?,'%')
debug [main] - ==> parameters: ad(string)
trace [main] - <== columns: id, user_name, user_password, user_email, create_time
trace [main] - <== row: 1, admin, 123456, admin@mybatis.tk, 2019-06-27 18:21:07.0
debug [main] - <== total: 1
debug [main] - ==> preparing: select id, user_name, user_password, user_email, create_time from sys_user where user_email = ?
debug [main] - ==> parameters: test@mybatis.tk(string)
trace [main] - <== columns: id, user_name, user_password, user_email, create_time
trace [main] - <== row: 1001, test, 123456, test@mybatis.tk, 2019-06-27 18:21:07.0
debug [main] - <== total: 1
debug [main] - ==> preparing: select id, user_name, user_password, user_email, create_time from sys_user where user_name like concat('%',?,'%') and user_email = ?
debug [main] - ==> parameters: ad(string), test@mybatis.tk(string)
debug [main] - <== total: 0
3. set 用法
set标签的作用:如果该标签包含的元素中有返回值,就插入一个set,如果set后面的字符串是以,结尾的,就将这个逗号剔除。
假设有这样1个需求:更新用户信息的时候不能将原来有值但没有发生变化的字段更新为空或null,即只更新有值的字段。
首先,我们在接口sysusermapper中添加如下方法:
/** * 根据主键选择性更新用户信息(使用set标签) * * @param sysuser * @return */ int updatebyidselectiveset(sysuser sysuser);
然后在对应的sysusermapper.xml中添加如下代码:
<update id="updatebyidselectiveset"> update sys_user <set> <if test="username != null and username != ''"> user_name = #{username}, </if> <if test="userpassword != null and userpassword != ''"> user_password = #{userpassword}, </if> <if test="useremail != null and useremail != ''"> user_email = #{useremail}, </if> <if test="userinfo != null and userinfo != ''"> user_info = #{userinfo}, </if> <if test="headimg != null"> head_img = #{headimg,jdbctype=blob}, </if> <if test="createtime != null"> create_time = #{createtime,jdbctype=timestamp}, </if> id = #{id}, </set> where id = #{id} </update>
注意事项:为了避免所有的条件都不满足,生成的sql语句没有set标签,因此在最后加上了id = #{id},
这样必然存在的赋值。
最后,在sysusermappertest测试类中添加如下测试方法:
@test public void testupdatebyidselectiveset() { sqlsession sqlsession = getsqlsession(); try { sysusermapper sysusermapper = sqlsession.getmapper(sysusermapper.class); sysuser sysuser = new sysuser(); // 更新id=1的用户 sysuser.setid(1l); // 修改邮箱 sysuser.setuseremail("test@mybatis.tk"); int result = sysusermapper.updatebyidselectiveset(sysuser); assert.assertequals(1, result); // 查询id=1的用户 sysuser = sysusermapper.selectbyid(1l); // 修改后的名字保持不变,但是邮箱变成了新的 assert.assertequals("admin", sysuser.getusername()); assert.assertequals("test@mybatis.tk", sysuser.getuseremail()); } finally { sqlsession.close(); } }
运行测试代码,测试通过,输出日志如下:
debug [main] - ==> preparing: update sys_user set user_email = ?, id = ? where id = ?
debug [main] - ==> parameters: test@mybatis.tk(string), 1(long), 1(long)
debug [main] - <== updates: 1
debug [main] - ==> preparing: select id, user_name, user_password, user_email, create_time from sys_user where id = ?
debug [main] - ==> parameters: 1(long)
trace [main] - <== columns: id, user_name, user_password, user_email, create_time
trace [main] - <== row: 1, admin, 123456, test@mybatis.tk, 2019-06-27 18:21:07.0
debug [main] - <== total: 1
4. 源码
源码地址:,欢迎下载。
5. 参考
刘增辉《mybatis从入门到精通》