MyBatis动态SQL

前端之家收集整理的这篇文章主要介绍了MyBatis动态SQL前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

项目的创建和之前一样,具体的看之前的文章,整体结构就是这样

一、if

对于该标签的执行,当 test 的值为 true 时,会将其包含的 sql 片断拼接到其所在的 sql 语句中。
语法:<if test=”条件”> sql 语句的部分 </if>

接口方法:StudentDao

  1. // 动态的sql时,使用java对象作为参数
  2. List<Student> selectStudentIf(Student student);

mapper文件:StudentDao.xml

  1. <!--if的使用
  2. <if test="使用的参数为java对象属性值作为判断条件">
  3. 语法:属性=xxx值
  4. -->
  5. <!--
  6. 注意,当这样写的时候,name不满足而age满足的时候会出现问题
  7. 正常:select id,name,age,email from student where name = ? or age > ?
  8. 不正常: select id,email from student where or age > ?
  9. 这个时候会有语法错误
  10. 所以写的是时候要在where后面这样
  11. where 1=1
  12. 这样写的话即使name不满足,后面的也不不会出现语法错误
  13. select id,email from student where 1=1 or age > ?
  14. 但这样也会出现其他的bug,因为是or,并且1=1永远为true,所以age无论传入多大都会有数据的
  15. -->
  16. <select id="selectStudentIf" resultType="com.md.domain.Student">
  17. select id,email from student
  18. where 1=1
  19. <if test="name != null and name != '' ">
  20. name = #{name}
  21. </if>
  22. <if test="age > 0" >
  23. or age > #{age}
  24. </if>
  25. </select>

测试

  1. @Test
  2. public void testSelectStudentIf(){
  3. sqlSession sqlSession = MybatisUtils.getsqlSession();
  4. StudentDao dao = sqlSession.getMapper(StudentDao.class);
  5. Student student = new Student();
  6. student.setAge(20);
  7. List<Student> studentList = dao.selectStudentIf(student);
  8. studentList.forEach(stu-> System.out.println(stu));
  9. sqlSession.close();
  10. }

此时即使数据库中,无论年纪多大的都会被查出来,所以就有了下面的标签

二、where

<if/>标签的中存在一个比较麻烦的地方:需要在 where 后手工添加 1=1 的子句。因为,若 where 后
的所有<if/>条件均为 false,而 where 后若又没有 1=1 子句,则 sql 中就会只剩下一个空的 where,sql
出错。所以,在 where 后,需要添加永为真子句 1=1,以防止这种情况的发生。但当数据量很大时,会
严重影响查询效率

使用<where/>标签,在有查询条件时,可以自动添加上 where 子句;没有查询条件时,不会添加where 子句。需要注意的是,第一个<if/>标签中的 sql 片断,可以不包含 and。不过,写上 and 也不错,系统会将多出的 and 去掉。但其它<if/>中 sql 片断的 and,必须要求写上。否则 sql 语句将拼接出错

<where> 用来包含 多个<if>的, 当多个if有一个成立的, <where>会自动增加一个where关键字,并去掉 if中多余的 and ,or等

语法:<where> 其他动态 sql </where>

接口方法

  1. // 动态的sql时,使用java对象作为参数
  2. List<Student> selectStudentWhere(Student student);

mapper

  1. <!--where的使用
  2. select id,email from student WHERE name = ? or age > ?
  3. select id,email from student WHERE age > ?
  4. 这样就避免了上面的bug
  5. -->
  6. <select id="selectStudentWhere" resultType="com.md.domain.Student">
  7. select id,email from student
  8. <where>
  9. <if test="name != null and name != '' ">
  10. name = #{name}
  11. </if>
  12. <if test="age > 0" >
  13. or age > #{age}
  14. </if>
  15. </where>
  16. </select>

测试:

  1. @Test
  2. public void testSelectStudentWhere(){
  3. sqlSession sqlSession = MybatisUtils.getsqlSession();
  4. StudentDao dao = sqlSession.getMapper(StudentDao.class);
  5. Student student = new Student();
  6. student.setName("白昊天");
  7. student.setAge(20);
  8. List<Student> studentList = dao.selectStudentWhere(student);
  9. studentList.forEach(stu-> System.out.println(stu));
  10. sqlSession.close();
  11. }

此时就不会出现之前的bug了

三、foreach

<foreach/>标签用于实现对于数组与集合的遍历。对其使用,需要注意:

  • collection 表示要遍历的集合类型,list ,array 等。
  • open、close、separator 为对遍历内容sql 拼接

语法

  1. <foreach collection=" 集合类型" open=" 开始的字符" close=" 结束的字符"
  2. item=" 集合中的成员" separator=" 集合成员之间的分隔符">
  3. #{item 的值}
  4. </foreach>

例子,查询学号1001、1002、1003学生的信息

如果是用纯java来拼接这个查询sql语句

  1. @Test
  2. public void testfor(){
  3. List<Integer> list = new ArrayList<>();
  4. list.add(1001);
  5. list.add(1002);
  6. list.add(1003);
  7. String sql = "select * from student where id in";
  8. StringBuilder builder = new StringBuilder("");
  9. // 添加开始
  10. builder.append("(");
  11. for (Integer i : list){
  12. builder.append(i).append(",");
  13. }
  14. // 因为最后多添加了一个逗号,所以在这里进行删除
  15. builder.deleteCharAt(builder.length()-1);
  16. builder.append(")");
  17. sql = sql + builder.toString();
  18. System.out.println(sql);
  19. // select * from student where id in(1001,1002,1003)
  20. }

1. 用法

接口

  1. // 传入的是普通list
  2. List<Student> selectForeachOne(List<Integer> idlist);

mapper

select id,email from student where id in ( ?,?,? )

  1. <select id="selectForeachOne" resultType="com.md.domain.Student">
  2. select id,email from student where id in
  3. <foreach collection="list" item="myid" open="(" close=")" separator=",">
  4. #{myid}
  5. </foreach>
  6. </select>

测试:

  1. @Test
  2. public void testSelectForeachOne(){
  3. sqlSession sqlSession = MybatisUtils.getsqlSession();
  4. StudentDao dao = sqlSession.getMapper(StudentDao.class);
  5. List<Integer> list = new ArrayList<>();
  6. list.add(1001);
  7. list.add(1002);
  8. list.add(1003);
  9. List<Student> studentList = dao.selectForeachOne(list);
  10. studentList.forEach(stu-> System.out.println(stu));
  11. sqlSession.close();
  12. }

2. 用法

接口

  1. // foreach 用法二 , 传入的是对象集合
  2. List<Student> selectForeachTwo(List<Student> stulist);

mapper文件

由于传入的是对象,所以要用对象.属性

  1. <select id="selectForeachTwo" resultType="com.md.domain.Student">
  2. select id,email from student where id in
  3. <foreach collection="list" item="stu" open="(" close=")" separator=",">
  4. #{stu.id}
  5. </foreach>
  6. </select>

测试方法

  1. @Test
  2. public void testSelectForeachTwo(){
  3. sqlSession sqlSession = MybatisUtils.getsqlSession();
  4. StudentDao dao = sqlSession.getMapper(StudentDao.class);
  5. List<Student> students = new ArrayList<>();
  6. Student stu1 = new Student();
  7. stu1.setId(1003);
  8. students.add(stu1);
  9. List<Student> studentList = dao.selectForeachTwo(students);
  10. studentList.forEach(stu-> System.out.println(stu));
  11. // select id,email from student where id in ( ? )
  12. // Student{id=1003,name='白昊天',email='ht@qq.com',age=18}
  13. sqlSession.close();
  14. }

当然了,对于mapper文件sql语句还可以这样写

  1. <!-- 直接在外面写小括号,只有能凑成完成的sql语句就行-->
  2. <select id="selectForeachTwo" resultType="com.md.domain.Student">
  3. select id,email from student where id in (
  4. <foreach collection="list" item="stu" separator=",">
  5. #{stu.id}
  6. </foreach>
  7. )
  8. </select>

效果和上面的是一样的,能完成的拼凑出sql语句即可

四、sql代码片段

<sql/>标签用于定义 sql 片断,以便其它 sql 标签复用。

而其它标签使用该 sql 片断,需要使用<include/>子标签。该<sql/>标签可以定义 sql 语句中的任何部分,所以<include/>子标签可以放在动态 sql的任何位置

接口方法

  1. List<Student> selectStudentsqlFragment(List<Student> stuList);

mapper文件

  1. <!-- 创建 sql 片段 id: 片段的自定义名称 -->
  2. <sql id="studentsql">
  3. select id,email,age from student
  4. </sql>
  5. <select id="selectStudentsqlFragment" resultType="com.md.domain.Student">
  6. <!-- 引用 sql 片段 -->
  7. <include refid="studentsql"/>
  8. <if test="list !=null and list.size > 0 ">
  9. where id in
  10. <foreach collection="list" open="(" close=")"
  11. item="stuobject" separator=",">
  12. #{stuobject.id}
  13. </foreach>
  14. < /if>
  15. </select>

测试方法

  1. @Test
  2. public void testSelectsqlFragment() {
  3. List<Student> list = new ArrayList<>();
  4. Student s1 = new Student();
  5. s1.setId(1002);
  6. list.add(s1);
  7. s1 = new Student();
  8. s1.setId(1005);
  9. list.add(s1);
  10. List<Student> studentList = studentDao.selectStudentsqlFragment(list);
  11. studentList.forEach( stu -> System.out.println(stu));
  12. }

五、总结

根据条件能够使用不同的sql语句,使用mybatis标签

1. if

判断条件,条件为true,就会把if之前的sql加入到主sql语句之后

2. where

<where> 标签里面多个if标签,如果有一个if判断为true,就会在sql的后面加入where关键字,而还会自动的去掉无用的and、or等字符

3. foreach

循环数组,list集合,主要看语法格式

4. sql代码片段

复用常用的sql语句

  • 先定义<sql id="自定义名唯一" > sql语句 </sql>
  • 再使用 <include refid = "id的值">

猜你在找的Mybatis相关文章