在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

Java的MyBatis框架中对数据库进行动态SQL查询的教程

2016-7-29 15:41| 发布者: zhangjf| 查看: 632| 评论: 0

摘要: 其实MyBatis具有的一个强大的特性之一通常是它的动态 SQL 能力。 如果你有使用 JDBC 或其他 相似框架的经验,你就明白要动态的串联 SQL 字符串在一起是十分纠结的,确保不能忘了空格或在列表的最后省略逗号。Mybatis ...

其实MyBatis具有的一个强大的特性之一通常是它的动态 SQL 能力。 如果你有使用 JDBC 或其他 相似框架的经验,你就明白要动态的串联 SQL 字符串在一起是十分纠结的,确保不能忘了空格或在列表的最后省略逗号。Mybatis中的动态 SQL 可以彻底处理这种痛苦。对于动态SQL,最通俗简单的方法就是我们自己在硬编码的时候赋予各种动态行为的判断,而在Mybatis中,用一种强大的动态 SQL 语 言来改进这种情形,这种语言可以被用在任意映射的 SQL 语句中。动态 SQL 元素和使用 JSTL 或其他相似的基于 XML 的文本处理器相似。MyBatis 采用功能强大的基于 OGNL 的表达式来消除其他元素。
我们常用的几个节点元素有if,choose(when, otherwise),trim(where, if),foreach。真正使用下来我感觉有点像XSLT(文章后面会顺带提一下~)的用法。
(1)if 的用法

在ViisitMapper的分页配置中,如果pageIndex>-1 and pageSize>-1的时候就加入相应的分页SQL,否则就不添加(默认取全部),如下:

  1. <select id="getListByPagenate" parameterType="PagenateArgs"
  2. resultType="Visitor">
  3. select * from (
  4. <include refid="getListSql" /> <include refid="orderBySql"/>
  5. ) t <!-- #{}表示参数化输出,${}表示直接输出不进行任何转义操作,自己进行转移 -->
  6. <if test="pageStart>-1 and pageSize>-1">
  7. limit #{pageStart}, #{pageSize}
  8. </if>
  9. </select>
  10. <sql id="getListSql">
  11. select * from Visitor where
  12. status>0
  13. </sql>
  14. <sql id="orderBySql">
  15. order by ${orderFieldStr} ${orderDirectionStr}
  16. </sql>
复制代码

  因为我们的参数pageIndex与pageSize都是int值所以可以这样直接判断,如果是对象实例我们可以利用null判断来进行一些动态逻辑的控制,具体实际开发中就要看业务需求了。这里我认为要注意的是别十分顺手的吧and写成&&,这个在配置中不会被识别~。

(2)choose (when, otherwise)的用法

  choose when 主要在多个条件的情况下只满足其中一个条件的应用场景中使用,例如这里就构建一个query条件,分别传递id,name与createTime。假设我们查询Visitor表时,如果VisitorId有值则,使用Id查询,如果VisitorName有值则采用VisitName查询,如下,还是在david.mybatis.demo.IVisitorOperation接口类中添加List getListChooseWhenDemo(BasicQueryArgs args)方法。在VisitorMapper中添加相应的的select节点配置:

  1. package david.mybatis.demo;
  2. import java.util.List;
  3. import david.mybatis.model.BasicQueryArgs;
  4. import david.mybatis.model.PagenateArgs;
  5. import david.mybatis.model.Visitor;
  6. import david.mybatis.model.VisitorWithRn;
  7. public interface IVisitorOperation {
  8. /*
  9. * 添加访问者
  10. */
  11. public int add(Visitor visitor);
  12. /*
  13. * 删除访问者
  14. */
  15. public int delete(int id);
  16. /*
  17. * 更新访问者
  18. */
  19. public int update(Visitor visitor);
  20. /*
  21. * 查询访问者
  22. */
  23. public Visitor query(int id);
  24. /*
  25. * 查询List
  26. */
  27. public List<Visitor> getList();
  28. /*
  29. * 分页查询List
  30. */
  31. public List<Visitor> getListByPagenate(PagenateArgs args);
  32. /*
  33. * 分页查询List(包含Rownum)
  34. */
  35. public List<VisitorWithRn> getListByPagenateWithRn(PagenateArgs args);
  36. /*
  37. * 基础查询
  38. */
  39. public Visitor basicQuery(int id);
  40. /*
  41. * 动态条件查询(choose,when)实例
  42. */
  43. public List<Visitor> getListChooseWhenDemo(BasicQueryArgs args);
  44. /*
  45. * 动态条件查询(where,if)实例
  46. */
  47. public List<Visitor> getListWhereDemo(BasicQueryArgs args);
  48. /*
  49. * 动态查询(foreach)实例
  50. */
  51. public List<Visitor> getListForeachDemo(List<Integer> ids);
  52. }
复制代码
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="david.mybatis.demo.IVisitorOperation">
  6. <resultMap type="Visitor" id="visitorRs">
  7. <id column="Id" property="id" />
  8. <result column="Name" property="name" />
  9. <result column="Email" property="email" />
  10. <result column="Status" property="status" />
  11. <result column="CreateTime" property="createTime" />
  12. </resultMap>
  13. <sql id="getListSqlConditions">
  14. select * from Visitor
  15. </sql>
  16. <!-- 满足其中一个条件时候用choose when操作 -->
  17. <select id="getListChooseWhenDemo" resultMap="visitorRs"
  18. parameterType="BasicQueryArgs">
  19. <include refid="getListSqlConditions" />
  20. <where>
  21. <if test="queryStatus>0">
  22. status=#{queryStatus}
  23. </if>
  24. <choose>
  25. <when test="queryId!=0">
  26. and id=#{queryId}
  27. </when>
  28. <when test="queryName!=null">
  29. and name like #{queryName}
  30. </when>
  31. <otherwise>
  32. and createTime>= #{queryTime}
  33. </otherwise>
  34. </choose>
  35. </where>
  36. </select>
  37. </mapper>
复制代码

(3)where if (trim)的用法

where关键词的好处是在于,如果有相应的过滤条件的话,它知道在适当的时候插入where关键词。而且它也知道在何时该去掉相应的AND与OR的连接符,主要应对如下情景

  1. <select id="findActiveBlogLike"
  2. resultType="Blog">
  3. SELECT * FROM BLOG
  4. WHERE
  5. <if test="state != null">
  6. state = #{state}
  7. </if>
  8. <if test="title != null">
  9. AND title like #{title}
  10. </if>
  11. <if test="author != null and author.name != null">
  12. AND author_name like #{author.name}
  13. </if>
  14. </select>
复制代码

不会因为所有条件不满足变为

  1. <select id="findActiveBlogLike"
  2. resultType="Blog">
  3. SELECT * FROM BLOG
  4. WHERE
  5. </select>
复制代码

或者因为没有满足第一个条件,单单满足后面的条件变成

  1. <select id="findActiveBlogLike"
  2. resultType="Blog">
  3. SELECT * FROM BLOG
  4. WHERE
  5. AND title like ‘someTitle'
  6. </select>
复制代码

所以针对这种我们可以在建立choose when条件示例,同样在IVisitorOperation接口类中加入相应的方法public List getListWhereDemo(BasicQueryArgs args),把VisitorMapper配置文件中的相对应配置加上去如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="david.mybatis.demo.IVisitorOperation">
  6. <sql id="getListSqlConditions">
  7. select * from Visitor
  8. </sql>
  9. <!-- 满足条件的都加上去操作 -->
  10. <select id="getListWhereDemo" resultMap="visitorRs"
  11. parameterType="BasicQueryArgs">
  12. <include refid="getListSqlConditions" />
  13. <where>
  14. <if test="queryStatus>0">
  15. status>0
  16. </if>
  17. <if test="queryId>0">
  18. and id=#{queryId}
  19. </if>
  20. <if test="queryName!=null">
  21. and name like=#{queryName}
  22. </if>
  23. <if test="queryTime!=null">
  24. and createTime>=#{queryTime}
  25. </if>
  26. </where>
  27. <!--
  28. <trim prefix="WHERE" prefixOverrides="AND |OR ">
  29. <if test="queryStatus>0">
  30. status>0
  31. </if>
  32. <if test="queryId>0">
  33. and id=#{queryId}
  34. </if>
  35. <if test="queryName!=null">
  36. and name like=#{queryName}
  37. </if>
  38. <if test="queryTime!=null">
  39. and createTime>=#{queryTime}
  40. </if>
  41. </trim>
  42. -->
  43. </select>
  44. </mapper>
复制代码

(4)foreach的用法

在常用的动态SQL中我们有个业务场景是要where id in 一大串的ID,像这种情况我们就可以用到foreach啦,不必自己辛辛苦苦去拼接Id字符串啦。同样的步骤还是在IVisitorOperation接口类中加入相应的方法public List getListForeachDemo(List ids),然后再对应的Mapper文件中配置上相应的节点元素信息,如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="david.mybatis.demo.IVisitorOperation">
  6. <sql id="getListSqlConditions">
  7. select * from Visitor
  8. </sql>
  9. <!-- Foreach循环条件 -->
  10. <select id="getListForeachDemo" resultMap="visitorRs">
  11. <include refid="getListSqlConditions"/>
  12. where status>0 and id in
  13. <foreach collection="list" item="item" index="index" open="(" separator="," close=")">
  14. ${item}
  15. </foreach>
  16. </select>
  17. </mapper>
复制代码

最后你只需要在DemoRun中建立相应的测试方法,Mybatis里面的动态SQL也就完成啦,下面测试用的DemoRun方法

  1. /*
  2. * 动态查询foreach实例
  3. */
  4. public static void getListForeachDemo(List<Integer> ids) {
  5. SqlSession session = MybatisUtils.getSqlSession();
  6. IVisitorOperation vOperation = session.getMapper(IVisitorOperation.class);
  7. List<Visitor> ls = vOperation.getListForeachDemo(ids);
  8. for (Visitor visitor : ls) {
  9. System.out.println(visitor);
  10. }
  11. }
  12. /*
  13. * 动态查询where if实例
  14. */
  15. public static void getListWhereCondition(int id, String name, Date createTime) {
  16. name = name == "" ? null : name;
  17. SqlSession session = MybatisUtils.getSqlSession();
  18. BasicQueryArgs args = new BasicQueryArgs(id, name, createTime);
  19. IVisitorOperation vOperation = session.getMapper(IVisitorOperation.class);
  20. List<Visitor> ls = vOperation.getListWhereDemo(args);
  21. if (ls.size() == 0)
  22. System.out.println("查无匹配!");
  23. else {
  24. for (Visitor visitor : ls) {
  25. System.out.println(visitor);
  26. }
  27. }
  28. }
  29. /*
  30. * 动态查询choose when实例
  31. */
  32. public static void getListChooseWhenDemo(int id, String name, Date createTime) {
  33. name = name == "" ? null : name;
  34. SqlSession session = MybatisUtils.getSqlSession();
  35. BasicQueryArgs args = new BasicQueryArgs(id, name, createTime);
  36. IVisitorOperation vOperation = session.getMapper(IVisitorOperation.class);
  37. List<Visitor> ls = vOperation.getListChooseWhenDemo(args);
  38. if (ls.size() == 0)
  39. System.out.println("查无匹配!");
  40. else {
  41. for (Visitor visitor : ls) {
  42. System.out.println(visitor);
  43. }
  44. }
  45. }
复制代码

201646151131782.png (795×440)
PS:关于OGNL
OGNL 是 Object-Graph Navigation Language 的缩写,从语言角度来说:它是一个功能强大的表达式语言,用来获取和设置 java 对象的属性 , 它旨在提供一个更高抽象度语法来对 java 对象图进行导航,OGNL 在许多的地方都有应用,例如:
作为 GUI 元素(textfield,combobox, 等)到模型对象的绑定语言。
数据库表到 Swing 的 TableModel 的数据源语言。
web 组件和后台 Model 对象的绑定语言 (WebOGNL,Tapestry,WebWork,WebObjects) 。
作为 Jakarata Commons BeanUtils 或者 JSTL 的表达式语言的一个更具表达力的替代语言。
另外,java 中很多可以做的事情,也可以使用 OGNL 来完成,例如:列表映射和选择。 对于开发者来说,使用 OGNL,可以用简洁的语法来完成对 java 对象的导航。通常来说: 通过一个“路径”来完成对象信息的导航,这个“路径”可以是到 java bean 的某个属性,或者集合中的某个索引的对象,等等,而不是直接使用 get 或者 set 方法来完成。

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-6 09:53

Copyright 2015-2025 djqfx

返回顶部