Mybatis学习总结之动态SQL与模糊查询

来源:互联网 发布:南昌seo自动优化软件 编辑:程序博客网 时间:2024/04/30 22:28

动态查询?模糊查询?说白了就是按照条件来查询,看了之前博文,你也许会问:在Mybatis中,如果按照某几个条件查询应该怎么做?比如,我要查询年龄在1到12岁之前,名字里还有字母o的用户。

其实,Mybatis的做法就是,为这种条件创建一个条件类,然后作为映射的parameterType传入。具体如下:

我们先给出类定义和数据库定义:


[sql] view plain copy
 print?
  1. create table d_user(    
  2.     id int primary key auto_increment,    
  3.     name varchar(10),  
  4.     age int(3)  
  5. );   
  6.    
  7. insert into d_user(name,age) values('Tom',12);    
  8. insert into d_user(name,age) values('Bob',13);    
  9. insert into d_user(name,age) values('Jack',18);  

User类:


[java] view plain copy
 print?
  1. package com.happyBKs.mybatis.C1_1.beans;  
  2.    
  3. public class User {  
  4.     private int id;  
  5.     private String name;  
  6.     private int age;  
  7.     public int getId() {  
  8.         return id;  
  9.     }  
  10.     public void setId(int id) {  
  11.         this.id = id;  
  12.     }  
  13.     public String getName() {  
  14.         return name;  
  15.     }  
  16.     public void setName(String name) {  
  17.         this.name = name;  
  18.     }  
  19.     public int getAge() {  
  20.         return age;  
  21.     }  
  22.     public void setAge(int age) {  
  23.         this.age = age;  
  24.     }  
  25.     public User(int id, String name, int age) {  
  26.         super();  
  27.         this.id = id;  
  28.         this.name = name;  
  29.         this.age = age;  
  30.     }  
  31.     public User() {  
  32.         super();  
  33.     }  
  34.     @Override  
  35.     public String toString() {  
  36.         return "User [id=" + id + ", name=" + name + ", age=" + age + "]";  
  37.     }  
  38.    
  39. }  

怎么定义条件“年龄在1到12岁之前,名字里还有字母o的用户。”?定义一个条件查询类 ConditionUser类

[java] view plain copy
 print?
  1. package com.happyBKs.mybatis.C1_1.beans;  
  2.    
  3. public class ConditionUser {  
  4.     private String name;  
  5.     private int minAge;  
  6.     private int maxAge;  
  7.     public String getName() {  
  8.         return name;  
  9.     }  
  10.     public void setName(String name) {  
  11.         this.name = name;  
  12.     }  
  13.     public int getMinAge() {  
  14.         return minAge;  
  15.     }  
  16.     public void setMinAge(int minAge) {  
  17.         this.minAge = minAge;  
  18.     }  
  19.     public int getMaxAge() {  
  20.         return maxAge;  
  21.     }  
  22.     public void setMaxAge(int maxAge) {  
  23.         this.maxAge = maxAge;  
  24.     }  
  25.     public ConditionUser(String name, int minAge, int maxAge) {  
  26.         super();  
  27.         this.name = name;  
  28.         this.minAge = minAge;  
  29.         this.maxAge = maxAge;  
  30.     }  
  31.     public ConditionUser() {  
  32.         super();  
  33.     }  
  34.     @Override  
  35.     public String toString() {  
  36.         return "ConditionUser [name=" + name + ", minAge=" + minAge  
  37.                 + ", maxAge=" + maxAge + "]";  
  38.     }  
  39.    
  40. }  

然后映射文件userMapper.xml写为:

[html] view plain copy
 print?
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  3. <mapper namespace="com.happyBKs.mybatis.C1_1.userMapper">  
  4. <select id="getUser" parameterType="com.happyBKs.mybatis.C1_1.beans.ConditionUser"  
  5.     resultType="com.happyBKs.mybatis.C1_1.beans.User">  
  6.     select * from d_user where age>=#{minAge} and age<=#{maxAge}  
  7.     <if test='name!="%null%"'>and name like #{name}</if>  
  8. </select>  
  9. </mapper>  


发现了吧,这里可以用if,if标签是mybatis映射文件中的定义动态SQL的一种标签。这类标签有很多种。


MyBatis 的一个强大的特性之一通常是它的动态 SQL 能力。如果你有使用 JDBC 或其他相似框架的经验,你就明白条件地串联 SQL 字符串在一起是多么的痛苦,确保不能忘了空格或在列表的最后省略逗号。动态 SQL 可以彻底处理这种痛苦。通常使用动态 SQL 不可能是独立的一部分, MyBatis 当然使用一种强大的动态 SQL 语言来改进这种情形,这种语言可以被用在任意映射的 SQL 语句中。

动态 SQL 元素和使用 JSTL 或其它相似的基于 XML 的文本处理器相似。 在 MyBatis 之前的版本中,有很多的元素需要来了解。 MyBatis 3 大大提升了它们,现在用不到原先一半的元素就能工作了。 MyBatis 采用功能强大的基于 OGNL 的表达式来消除其他元素。

if

choose(when,otherwise)

trim(where,set)

foreach

if

在动态 SQL 中所做的最通用的事情是包含部分 where 字句的条件。比如:


[html] view plain copy
 print?
  1. select id="findActiveBlogWithTitleLike" parameterType=”Blog" resultType=”Blog">  
  2. SELECT * FROM BLOG WHERE state = "ACTIVE"  
  3. <if test="title != null">  
  4. AND title like #{title}  
  5. </if>  
  6. </select>  

这条语句会提供一个可选的文本查找功能。如果你没有传递 title,那么所有激活的博客

都会被返回。但是如果你传递了 title,那么就会查找相近的 title(对于敏锐的检索,这中情

况下你的参数值需要包含任意的遮掩或通配符)的博客。

假若我们想可选地搜索 title 和 author 呢?首先,要改变语句的名称让它有意义。然后

简单加入另外的一个条件。


[html] view plain copy
 print?
  1. <select id="findActiveBlogLike" parameterType="Blog" resultType="Blog">  
  2. SELECT * FROM BLOG WHERE state = „ACTIVE‟  
  3. <if test=”title != null”>  
  4. AND title like #{title}  
  5. </if>  
  6. <if test="author != null and author.name != null">  
  7. AND title like #{author.name}  
  8. </if>  
  9. </select>  

choose, when, otherwise

有时我们不想应用所有的条件,相反我们想选择很多情况下的一种。和 Java 中的 switch语句相似, MyBatis 提供 choose 元素。

我们使用上面的示例,但是现在我们来搜索当 title 提供时仅有 title 条件,当 author 提供时仅有 author 条件。如果二者都没提供,只返回 featured blogs(也许是由管理员策略地选择的结果列表,而不是返回大量没有意义的, 随机的博客结果列表)。


[html] view plain copy
 print?
  1. <select id="findActiveBlogLike" parameterType="Blog" resultType="Blog">  
  2. SELECT * FROM BLOG WHERE state = "ACTIVE"  
  3. <choose>  
  4. <when test=”title != null”>  
  5. AND title like #{title}  
  6. </when>  
  7. <when test="author != null and author.name != null">  
  8. AND title like #{author.name}  
  9. </when>  
  10. <otherwise>  
  11. AND featured = 1  
  12. </otherwise>  
  13. </choose>  
  14. </select>  

trim, where, set

前面的例子已经方便地处理了一个臭名昭著的动态 SQL 问题。 要考虑我们回到" if"示

例后会发生什么,但是这次我们将" ACTIVE = 1" 也设置成动态的条件。


[html] view plain copy
 print?
  1. <select id="findActiveBlogLike" parameterType="Blog" resultType="Blog">  
  2. SELECT * FROM BLOG   
  3. WHERE  
  4. <if test="state != null">  
  5. state = #{state}  
  6. </if>  
  7. <if test="title != null">  
  8. AND title like #{title}  
  9. </if>  
  10. <if test="author != null and author.name != null">  
  11. AND title like #{author.name}  
  12. </if>  
  13. </select>  

如果这些条件都没有匹配上将会发生什么?这条 SQL 结束时就会成这样:

SELECT * FROM BLOG

WHERE

这会导致查询失败。如果仅仅第二个条件匹配是什么样的?这条 SQL 结束时就会是这

样:

SELECT * FROM BLOG

WHERE

AND title like „someTitle‟

这个查询也会失败。这个问题不能简单的用条件来解决,如果你从来没有这样写过,那

么你以后也不会这样来写。

MyBatis 有一个简单的处理,这在 90%的情况下都会有用。而在不能使用的地方,你可

以自定义处理方式。加上一个简单的改变,所有事情都会顺利进行:


[html] view plain copy
 print?
  1. <select id="findActiveBlogLike" parameterType="Blog" resultType="Blog">  
  2. SELECT * FROM BLOG  
  3. <where>  
  4. <if test="state != null">  
  5. state = #{state}  
  6. </if>  
  7. <if test="title != null">  
  8. AND title like #{title}  
  9. </if>  
  10. <if test="author != null and author.name != null">  
  11. AND title like #{author.name}  
  12. </if>  
  13. </where>  
  14. </select>  

where 元素知道如果由被包含的标记返回任意内容,就仅仅插入" WHERE"。而且,如

果以" AND"或" OR"开头的内容,那么就会跳过 WHERE 不插入。

如果 where 元素没有做出你想要的,你可以使用 trim 元素来自定义。比如,和 where

元素相等的 trim 元素是:

<trim prefix="WHERE" prefixOverrides="AND |OR ">

</trim>

overrides 属性采用管道文本分隔符来覆盖,这里的空白也是重要的。它的结果就是移除

在 overrides 属性中指定的内容, 插入在 with 属性中的内容。

和动态更新语句相似的解决方案是 set。 set 元素可以被用于动态包含更新的列,而不包

含不需更新的。比如:


[html] view plain copy
 print?
  1. <update id="updateAuthorIfNecessary"  
  2. parameterType="domain.blog.Author">  
  3. update Author  
  4. <set>  
  5. <if test="username != null">username=#{username},</if>  
  6. <if test="password != null">password=#{password},</if>  
  7. <if test="email != null">email=#{email},</if>  
  8. <if test="bio != null">bio=#{bio}</if>  
  9. </set>  
  10. where id=#{id}  
  11. </update>  

这里, set 元素会动态前置 SET 关键字,而且也会消除任意无关的逗号,那也许在应用

条件之后来跟踪定义的值。

如果你对和这相等的 trim 元素好奇,它看起来就是这样的:

<trim prefix="SET" suffixOverrides=",">

</trim>

注意这种情况下我们覆盖一个后缀,而同时也附加前缀。

foreach

另外一个动态 SQL通用的必要操作是迭代一个集合,通常是构建在IN条件中的。比如:


[html] view plain copy
 print?
  1. <select id="selectPostIn" resultType="domain.blog.Post">  
  2. SELECT *  
  3. FROM POST P  
  4. WHERE ID in  
  5. <foreach item="item" index="index" collection="list"  
  6. open="(" separator="," close=")">  
  7. #{item}  
  8. </foreach>  
  9. </select>  

foreach 元素是非常强大的,它允许你指定一个集合,声明集合项和索引变量,它们可

以用在元素体内。它也允许你指定开放和关闭的字符串,在迭代之间放置分隔符。这个元素

是很智能的,它不会偶然地附加多余的分隔符。

注意:你可以传递一个 List 实例或者数组作为参数对象传给 MyBatis。当你这么做的时

候, MyBatis 会自动将它包装在一个 Map 中,用名称作为键。 List 实例将会以" list"

作为键,而数组实例将会以" array"作为键。

这个部分是对关于 XML 配置文件和 XML 映射文件的而讨论的。下一部分将详细讨论

Java API,所以你可以得到你已经创建的最有效的映射。

==========================================================================================================

好吧,回到本文的例子:

映射文件写好后,完成映射文件注册:

[html] view plain copy
 print?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  3. <configuration>  
  4.    
  5. <properties resource="db.properties"/>  
  6.    
  7.    
  8. <!--   
  9. development: 开发模式  
  10. work: 工作模式  
  11.  -->  
  12.     <environments default="development">  
  13.         <environment id="development">  
  14.             <transactionManager type="JDBC" />  
  15.             <dataSource type="POOLED">  
  16.                 <property name="driver" value="${driver}" />  
  17.                 <property name="url" value="${url}" />  
  18.                 <property name="username" value="${username}" />  
  19.                 <property name="password" value="${password}" />  
  20.             </dataSource>  
  21.         </environment>  
  22.     </environments>  
  23.        
  24.     <!-- 在conf.xml文件中注册userMapper.xml文件 -->  
  25.     <mappers>  
  26.         <mapper resource="com/happyBKs/mybatis/C1_1/beans/orderMapper.xml"/>  
  27.         <mapper resource="com/happyBKs/mybatis/C1_1/beans/orderMapper2.xml"/>  
  28.         <mapper resource="com/happyBKs/mybatis/C1_1/beans/classMapper.xml"/>   
  29.         <mapper resource="com/happyBKs/mybatis/C1_1/beans/classMapper2.xml"/>      
  30.         <mapper resource="com/happyBKs/mybatis/C1_1/beans/classMapper3.xml"/>  
  31.         <mapper resource="com/happyBKs/mybatis/C1_1/beans/classMapper4.xml"/>  
  32.         <mapper resource="com/happyBKs/mybatis/C1_1/beans/userMapper.xml"/>    
  33.     </mappers>  
  34.    
  35. </configuration>  


然后,编写测试程序


[java] view plain copy
 print?
  1. package com.happyBKs.mybatis.C1_1;  
  2.    
  3. import java.io.IOException;  
  4. import java.io.Reader;  
  5. import java.util.List;  
  6.    
  7. import org.apache.ibatis.io.Resources;  
  8. import org.apache.ibatis.session.SqlSession;  
  9. import org.apache.ibatis.session.SqlSessionFactory;  
  10. import org.apache.ibatis.session.SqlSessionFactoryBuilder;  
  11. import org.junit.Test;  
  12.    
  13. import com.happyBKs.mybatis.C1_1.beans.ConditionUser;  
  14. import com.happyBKs.mybatis.C1_1.beans.User;  
  15.    
  16. public class TestCondition {  
  17.    
  18.     @Test  
  19.     public void test1()  
  20.     {  
  21.         Reader reader=null;  
  22.         try {  
  23.             reader = Resources.getResourceAsReader("config.xml");  
  24.         } catch (IOException e) {  
  25.             // TODO Auto-generated catch block  
  26.             e.printStackTrace();  
  27.         }  
  28.         SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);  
  29.         SqlSession sqlSession = sessionFactory.openSession();  
  30.         String statement = "com.happyBKs.mybatis.C1_1.userMapper.getUser";  
  31.         List<User> list = sqlSession.selectList(statement, new ConditionUser("%o%"112));     
  32.         System.out.println(list);  
  33.    
  34.     }  
  35. }  


结果:

[User [id=1, name=Tom, age=12]]

0 0