MyBatis动态SQL

2018-05-09 21:00:42
951次阅读
0个评论
1.where,if用法
如下面动态select的写法,当where句中的if判断的是参数中给的数据,而不是数据库中的值。若条件不成立的时候,则忽略where语句。
注意下面子句中使用了 and name like 这里的and会由MyBatis进行自动判断,若只有一个子句会自动被去掉。
<mapper namespace="dao.StudentMapper">  
  
    <select id="findStudentByName_Static" parameterType="mybatis.Student" resultType="mybatis.Student">  
        select * from student where name like "%${name}%"  
    </select>  
      
    <select id="findStudentByName_Dynamic" parameterType="mybatis.Student" resultType="mybatis.Student">  
        select * from student  
        <where>  
            <if test="name != null">  
                and name like "%${name}%"  
            </if>  
        </where>  
    </select>  
</mapper>


MyBatisTest.java
如下测试代码,当给的查询条件中name属性不进行设置,即name为null时,则不会添加 where name like 的子条件。该特性可以用于商品查询时用户添加的查询条件,若勾选则增加限制条件。比如招聘简历中,筛选工资范围,区域范围等。
<pre class="prettyprint lang-java">
<pre class="prettyprint lang-java">public class MybatisTest {  
    public static void main(String[] args) throws IOException{  
        InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");  
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);  
        SqlSession sqlSession = sqlSessionFactory.openSession(true);  
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);  
          
        Student target = new Student();  
        target.setAge(20);  
        target.setId(40);  
          
        try {  
            List<Student> list = studentMapper.findStudentByName_Dynamic(target); //查询  
            System.out.println(list);         
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}  </pre>


</pre>



2.SQL片段
为了可重用,可以将查询条件,判断条件等重复性的语句定义成SQL片段,类似于子函数。
SQL片段尽量使用在同一个数据表,这样列名,属性名等一致,可重用性会比较好。另外,为了使用多个查询条件时不会发生冲突,where字句尽量不要包含在SQL片段中。

<mapper namespace="dao.StudentMapper">  
  
    <sql id="query_student_where">  
        <if test="name != null">  
            and name like "%${name}%"  
        </if>  
    </sql>  
  
    <select id="findStudentByName_Static" parameterType="mybatis.Student" resultType="mybatis.Student">  
        select * from student where name like "%${name}%"  
    </select>  
      
    <select id="findStudentByName_Dynamic" parameterType="mybatis.Student" resultType="mybatis.Student">  
        select * from student  
        <where>  
            <include refid="query_student_where"></include>  
            <!-- where不包含在SQL片段中,在这里就比较方便追加多个SQL片段 -->  
        </where>  
    </select>  
</mapper>



3.for each
向sql传递数组活list时,MyBatis使用foreach进行解析。
用户查询列表和查询总数的statement中增加多个Id输入查询:select * from student where name="high" and  (id=1 or id=3 or id=5);
通过MyBatis实现的代码如下,同样若where中条件不成立,则会返回所有元素,即忽略掉where中的条件。

Mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper  
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
<mapper namespace="dao.StudentMapper">  
  
    <sql id="query_student_foreach">    
        <if test="list != null">  
            <!--  
                collection:是指需要遍历的属性,在ForSQLPO中对应的属性名   
                item 是for循环中的变量名,相当于for(i=1;...)中的i  
                open是指该子串的开始符号,close是指结束拼接符号  
                separator是指ids的每个条件之间连接时使用的内容     
             -->  
            <foreach collection="list" item="id" open="and (" close=")" separator="or">  
                <!-- foreach中内容为对每个id的处理 -->  
                id=#{id} <!-- 等价于 and ( id=#{id} or id={id}...) -->  
            </foreach>  
        </if>  
    </sql>  
      
    <select id="findStudentByName_Dynamic" parameterType="java.util.List" resultType="mybatis.Student">  
        select * from student  
        <where>  
            <include refid="query_student_foreach"></include>  
            <!-- where不包含在SQL片段中,在这里就比较方便追加多个SQL片段 -->  
        </where>  
    </select>  
</mapper>


测试代码如下:
public class MybatisTest {  
    public static void main(String[] args) throws IOException{  
        InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");  
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);  
        SqlSession sqlSession = sqlSessionFactory.openSession(true);  
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);  
          
        List<Integer> ids = new ArrayList<Integer>();  
        ids.add(34);  
        ids.add(35);  
        ids.add(36);  
          
        try {  
            List<Student> list = studentMapper.findStudentByName_Dynamic(ids); //查询  
            System.out.println(list);         
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}


收藏00

登录 后评论。没有帐号? 注册 一个。