好程序员Java分享Mybatis必会的动态SQL,前言
Mybatis可谓是java开发者必须会的一项技能。MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其它类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句的痛苦。例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。
![1b86c4b8c6ce45c8e4c272c58b5d7fcd.png](https://i-blog.csdnimg.cn/blog_migrate/fa6d5984b52ce31d43aeb9cef3146aab.jpeg)
Mybatis动态sql
mybatis 动态SQL,通过 if, choose, when, otherwise, trim, where, set, foreach等标签,可组合成非常灵活的SQL语句,从而在提高 SQL 语句的准确性的同时,也大大提高了开发人员的效率。本文主要介绍这几个动态SQL.
具体示例
if标签 if就是用来对输入映射的字段进行判断 一般是非空判断 null 和""。
1.
2. id="selectUsersIf" parameterType="user" resultType="user">
3. select * from users where 1=1
4. test="uname!=null and uname!=''"> and uname like "%"#{uname}"%"
5. test="sex!=null and sex!=''">and sex = #{sex}
6.
动态SQL 相当于 where关键字 可以自动处理第一个前and 或者or。 当条件都没有的时候 where也不会加上 。
1.
2. id="selectUsersWhere" parameterType="user" resultType="user">
3. select * from users
4.
5. test="uname!=null and uname!=''"> and uname like "%"#{uname}"%"
6. test="sex!=null and sex!=''">and sex = #{sex}
7.
choose—when--when--otherwise when可以多个 otherwise只能有一个 类似于 switch case。
需求:输入用户id 按照用户id进行精确查找 其他条件不看 没有输入 id 用户名模糊查找 都没有的话 查询id=1的用户
1.
2.
3. id="selectUsersChoose" parameterType="user" resultType="user">
4. select * from users
5.
6.
7. test="uid!=null"> uid=#{uid}
8. test="uname!=null and uname!=''"> uname like "%"#{uname}"%"
9. uid=1
10.
11.
12.
13.
动态sql之set 代替set关键字 set标签可以帮助我们去掉最后一个逗号
1. id="updateSet" parameterType="user">
2.
3. update users
4.
5.
6. test="uname!=null and uname!=''"> uname =#{uname},
7. test="upwd!=null and upwd!=''"> upwd =#{upwd},
8. test="sex!=null and sex!=''"> sex =#{sex},
9. test="birthday!=null"> birthday =#{birthday},
10.
11. where uid=#{uid}
12.
Trim,trim代替where
1.
2. id="selectUsersTrimWhere" parameterType="user" resultType="user">
3. select * from users
4.
2. id="updateTrimSet" parameterType="user">
3.
4. update users
5.
6. prefix="set" suffixOverrides=