mybatistools

一、SQL语句标签:

[html]  view plain  copy
  1. <!--查询语句-->  
  2. <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >  
  3.     select   
  4.   </select>  
  5.   
  6. <!--插入语句-->  
  7. <insert id="insert" parameterType="pojo.OrderTable" >  
  8.  insert into ordertable (order_id, cid, address,   
  9.       create_date, orderitem_id)  
  10.     values (#{orderId,jdbcType=VARCHAR}, #{cid,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR},   
  11.       #{createDate,jdbcType=TIMESTAMP}, #{orderitemId,jdbcType=VARCHAR})  
  12.   </insert>  
  13.   
  14. <!--删除语句-->  
  15. <delete id="deleteByPrimaryKey" parameterType="java.lang.String" >  
  16. delete from ordertable  
  17.     where order_id = #{orderId,jdbcType=VARCHAR}  
  18. </delete>  
  19.   
  20. <!--修改语句-->  
  21.  <update id="updateByPrimaryKey" parameterType="pojo.OrderTable" >  
  22.   update ordertable  
  23.     set cid = #{cid,jdbcType=VARCHAR},  
  24.       address = #{address,jdbcType=VARCHAR},  
  25.       create_date = #{createDate,jdbcType=TIMESTAMP},  
  26.       orderitem_id = #{orderitemId,jdbcType=VARCHAR}  
  27.     where order_id = #{orderId,jdbcType=VARCHAR}  
  28.   </update>  
需要配置的属性:id="xxxx" >>> 表示此段sql执行语句的唯一标识,也是接口的方法名称【必须一致才能找到】

parameterType="" >>>表示该sql语句中需要传入的参数, 类型要与对应的接口方法的类型一致【可选】

resultMap=“ ”>>> 定义出参,调用已定义的<resultMap>映射管理器的id值

resultType=“ ”>>>定义出参,匹配普通java类型或自定义的pojo【出参类型若不指定,将为语句类型默认类型,如<insert>语句返回值为int】

p.s: 至于为何<insert><delete><update> 语句的返回值类型为什么是int,有过JDBC操作经验的朋友可能会有印象,增删改操作实际上返回的是操作的条数。而Mybatis框架本身是基于JDBC的,所以此处也沿袭这种返回值类型。

传参和取值:mapper.xml 的灵活性还体现在SQL执行语句可以传参,参数类型通过parameterType= “” 定义

取值方式1:#{value jdbcType = valuetype}:jdbcType 表示该属性的数据类型在数据库中对应的类型,如 #{user jdbcType=varchar} 等价于 String username;

取值方式2:${value } : 这种方式不建议大量使用,可能会发送sql注入而导致安全性问题。一般该取值方式可用在非经常变化的值上,如orderby ${columnName};


二、sql片段标签<sql>:通过该标签可定义能复用的sql语句片段,在执行sql语句标签中直接引用即可。这样既可以提高编码效率,还能有效简化代码,提高可读性

     需要配置的属性:id="" >>>表示需要改sql语句片段的唯一标识

     引用:通过<include refid="" />标签引用,refid="" 中的值指向需要引用的<sql>中的id=“”属性

[html]  view plain  copy
  1. <!--定义sql片段-->  
  2. <sql id="orderAndItem">  
  3.     o.order_id,o.cid,o.address,o.create_date,o.orderitem_id,i.orderitem_id,i.product_id,i.count  
  4.   </sql>  
  5.   
  6.  <select id="findOrderAndItemsByOid" parameterType="java.lang.String" resultMap="BaseResultMap">  
  7.     select  
  8. <!--引用sql片段-->  
  9.     <include refid="orderAndItem" />  
  10.     from ordertable o  
  11.     join orderitem i on o.orderitem_id = i.orderitem_id  
  12.     where o.order_id = #{orderId}  
  13.   </select>  

三、映射管理器resultMap:映射管理器,是Mybatis中最强大的工具,使用其可以进行实体类之间的关系,并管理结果和实体类间的映射关系

     需要配置的属性:<resultMap id="  " type="  "></resutlMap>   id=" ">>>表示这个映射管理器的唯一标识,外部通过该值引用; type = " ">>> 表示需要映射的实体类;

     需要配置的参数:<id column = " " property= " " />    <id>标签指的是:结果集中结果唯一的列【column】 和 实体属性【property】的映射关系,注意:<id>标签管理的列未必是主键列,需要根据具体需求指定;

    <result column= " " property=" " />  <result>标签指的是:结果集中普通列【column】 和 实体属性【property】的映射关系;

            需要维护的关系:所谓关系维护是值在主表查询时将其关联子表的结果也查询出来

   1)一对一关系<assocation property = " " javaType=" ">   property = “ ” 被维护实体在宿主实体中的属性名,javaType = " " 被维护实体的类型

Orderitem.java

[java]  view plain  copy
  1. package pojo;  
  2.   
  3. public class Orderitem {  
  4.     
  5.     private String orderitemId;  
  6.   
  7.     private String productId;  
  8.   
  9.     private Integer count;  
  10.       
  11.     private Product product;     
从上方代码段可以看出:Product 对象在 Orderitem 实体中以 product 属性存在 

Orderitemmapper.xml

[html]  view plain  copy
  1. <resultMap id="BaseResultMap" type="pojo.Orderitem" >  
  2.    <id column="orderitem_id" property="orderitemId" jdbcType="VARCHAR" />  
  3.    <result column="product_id" property="productId" jdbcType="VARCHAR" />  
  4.    <result column="count" property="count" jdbcType="INTEGER" />  
  5.    <!-- 通过association 维护 一对一关系 -->  
  6.    <association property="product" javaType="pojo.Product">  
  7.     <id column="product_id" property="productId"/>  
  8.     <result column="product_factroy" property="productFactroy"/>  
  9.     <result column="product_store" property="productStore"/>  
  10.     <result column="product_descript" property="productDescript"/>  
  11.    </association>  
  12.  </resultMap>  
通过xml的配置可以看出,在resultMap映射管理器中,通过<association> 进行了维护,也就是在查询Orderitem对象时,可以把关联的Product对象的信息也查询出来


2)一对多关系的维护<collection property=" " ofType=" "> property = “ ” 被维护实体在宿主实体中的属性名 ,ofType=“ ”是被维护方在宿主类中集合泛型限定类型

【由于在一对多关系中,多的一放是以List形式存在,因此ofType的值取用Lsit<?> 的泛型对象类型】

OrderTable.java

[java]  view plain  copy
  1. public class OrderTable {  
  2.    
  3.     private String orderId;  
  4.   
  5.     private String cid;  
  6.   
  7.     private String address;  
  8.   
  9.     private Date createDate;  
  10.   
  11.     private String orderitemId;  
  12.      
  13.     private List<Orderitem> orderitemList ;  
[java]  view plain  copy
  1. }  
OrderTableMapper.xml;
[html]  view plain  copy
  1. <resultMap id="BaseResultMap" type="pojo.OrderTable" >  
  2.    <!--  
  3.      WARNING - @mbggenerated  
  4.      This element is automatically generated by MyBatis Generator, do not modify.  
  5.      This element was generated on Fri May 06 15:49:42 CST 2016.  
  6.    -->  
  7.    <id column="order_id" property="orderId" jdbcType="VARCHAR" />  
  8.    <result column="cid" property="cid" jdbcType="VARCHAR" />  
  9.    <result column="address" property="address" jdbcType="VARCHAR" />  
  10.    <result column="create_date" property="createDate" jdbcType="TIMESTAMP" />  
  11.    <result column="orderitem_id" property="orderitemId" jdbcType="VARCHAR" />  
  12.      <!--维护一对多的关系  -->  
  13.     <collection property="orderitemList" ofType="pojo.Orderitem">  
  14.         <id column="orderitem_id" property="orderitemId"/>  
  15.         <result column="product_id" property="productId"/>  
  16.         <result column="count" property="count"/>  
  17.     </collection>   
  18.  </resultMap>  

3)在resultMap 中需要注意两点:

3.1)关联关系的维护可以根据实体类之间的实际情况进行嵌套维护

[html]  view plain  copy
  1. <resultMap id="BaseResultMap" type="pojo.OrderTable" >  
  2.     <id column="order_id" property="orderId" jdbcType="VARCHAR" />  
  3.     <result column="cid" property="cid" jdbcType="VARCHAR" />  
  4.     <result column="address" property="address" jdbcType="VARCHAR" />  
  5.     <result column="create_date" property="createDate" jdbcType="TIMESTAMP" />  
  6.     <result column="orderitem_id" property="orderitemId" jdbcType="VARCHAR" />  
  7.          <!--维护一对多的关系  -->  
  8.         <collection property="orderitemList" ofType="pojo.Orderitem">  
  9.             <id column="orderitem_id" property="orderitemId"/>  
  10.             <result column="product_id" property="productId"/>  
  11.             <result column="count" property="count"/>  
  12. <span style="white-space:pre">        </span><!--嵌套一对一关系-->  
  13.             <association property="customer" javaType="pojo.Customer">  
  14.                 <id column="cid" property="cid"/>  
  15.                 <result column="cname" property="cname"/>  
  16.             </association>  
  17.         </collection>   
  18.   </resultMap>  
读者只用参考上方代码段的写法,实体关系仅为笔者举例没有必然的逻辑联系】

3.2)关于出现重复列名的处理:在实际操作过程中,查询到的结果可能会出现相同的列名,这样会对映射到实体属性带来影响甚至出现报错,那么对待这个问题可以通过对列取别名的方式处理


四:常用的动态语句标签:通过动态sql标签可以进行条件判断,条件遍历等操作从而满足结果的需要

 <where> : 使用其可以代替sql语句中的where关键字,一般防止在条件查询的最外层

         <if >:条件判断标签,配置属性test=" 条件字符串 ",判断是否满足条件,满足则执行,不满足则跳过

[html]  view plain  copy
  1. <select id="findOrderItemDetail" parameterType="pojo.Orderitem" resultMap="BaseResultMap">  
  2.         select orderitem.orderitem_id,product.*   
  3.         from orderitem,product  
  4.         <where>  
  5.             <if test="orderitemId!=null and orderitemId!=''">  
  6.                 and orderitem.orderitem_id = #{orderitemId}  
  7.             </if>  
  8.             <if test="productId!=null and productId!=''">  
  9.                 and orderitem.product_id = #{productId}  
  10.             </if>  
  11.             <if test="count!=null">  
  12.                 and orderitem.count = #{count}  
  13.             </if>  
  14.         </where>  
  15.   </select>  

<set>:常用于<update>更新语句中,替代 sql中的“set”关键字,特别是在联合<if>进行判断是,可以有效方式当某个参数为空或者不合法是错误的更新到数据库中

[html]  view plain  copy
  1. <update id="updateByPrimaryKeySelective" parameterType="pojo.Orderitem" >  
  2.    update orderitem  
  3.    <set >  
  4.      <if test="productId != null" >  
  5.        product_id = #{productId,jdbcType=VARCHAR},  
  6.      </if>  
  7.      <if test="count != null" >  
  8.        count = #{count,jdbcType=INTEGER},  
  9.      </if>  
  10.    </set>  
  11.    where orderitem_id = #{orderitemId,jdbcType=VARCHAR}  
  12.  </update>  

<choose><when></when><otherwise></otherwise></choose> 标签组:也是一个用于条件判断的标签组,和<if>的不同之处在于条件从<choose>进入,去匹配<when>中的添加,一旦匹配马上结束;若到找不到匹配项,将执行<other>中的语句;可以理解为<if>是 && 关系 <choose>是 || 关系

[html]  view plain  copy
  1. <!-- 查询学生list,like姓名、或=性别、或=生日、或=班级,使用choose -->       
  2. <select id="getStudentListChooseEntity" parameterType="StudentEntity" resultMap="studentResultMap">       
  3.     SELECT * from STUDENT_TBL ST        
  4.     <where>       
  5.         <choose>       
  6.             <when test="studentName!=null and studentName!='' ">       
  7.                     ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')        
  8.             </when>       
  9.             <when test="studentSex!= null and studentSex!= '' ">       
  10.                     AND ST.STUDENT_SEX = #{studentSex}        
  11.             </when>       
  12.             <when test="studentBirthday!=null">       
  13.                 AND ST.STUDENT_BIRTHDAY = #{studentBirthday}        
  14.             </when>       
  15.             <when test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">       
  16.                 AND ST.CLASS_ID = #{classEntity.classID}        
  17.             </when>       
  18.             <otherwise>       
  19.                         
  20.             </otherwise>       
  21.         </choose>       
  22.     </where>       
  23. </select>     
【注:以上代码段转载自:http://blog.csdn.net/zenson_g/article/details/10137665】


<foreach>标签:该标签的作用是遍历集合类型的条件 

  属性:collection=“array” / collection = “list”  ----->是数组类型,还是集合类型

              item=“ productId ”------> 参数名

      open="(" separator="," close=")"  ------>开始符号,分隔符号,结束符号 

      index=“ ” ---->结束下标位置,不配置该参数时,默认为全部遍历

[html]  view plain  copy
  1. <delete id="deleteByPriKeys" parameterType="java.lang.String">  
  2.      delete from product where product_Id in  
  3.      <foreach collection="list" item="productId" open="(" separator="," close=")">  
  4.          #{productId,jdbcType = VARCHAR}  
  5.      </foreach>  
  6.  </delete>   

------------------------------------------------------------------------------------------------------------------------------------------

_parameter

_parameter 表示当前传入的参数,如果查询的时候传入的参数只有一个,则使用 _parameter

?
1
E getById(Integer id);
?
1
2
3
4
5
6
7
<select id= "getById" parameterType= "int" resultMap= "BaseResultMap" >
     SELECT *
     FROM
     库名.表名
     WHERE
     id = #{_parameter}
   </select>

if判断

?
1
2
3
4
5
6
<select id= "getUsers" parameterType= "int" resultType= "User" >
     SELECT id, name, phone, email FROM users WHERE 1 = 1
     < if test= "_parameter != null" >
       and id > #{_parameter}
     </ if >
   </select>

大量重复的字段

?
1
2
3
<sql id= "HHHHH" >
     id,name
   </sql>

引用写法 

?
1
<include refid= "HHHHH" />

foreach

1、item表示集合中每一个元素进行迭代时的别名,

2、index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,

3、open表示该语句以什么开始,

4、separator表示在每次进行迭代之间以什么符号作为分隔符,

5、close表示以什么结束,

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<update id= "updateBatch" >
     <foreach item= "item" index= "index" collection= "list" open= ""
       close= "" separator= ";" >
       < if test= "item.statusType.toString() == 'DELETED'" >
         DELETE FROM 库名.表名 WHERE id = #{item.id}
       </ if >
       < if test= "item.statusType.toString() != 'DELETED'" >
         UPDATE 库名.表名
         <set>
           modifier = #{item.modifier,jdbcType=CHAR},
           < if test= "item.account != null" >
             account = #{item.account,jdbcType=VARCHAR},
           </ if >
           < if test= "item.name != null" >
             name = #{item.name,jdbcType=VARCHAR},
           </ if >
         </set>
         where
         库名.表名.id =#{item.id}
       </ if >
     </foreach>
   </update>

set


------------------------------------------------------------------------------------------------------------------------------------

sql语句where条件中,需要一些安全判断,例如按性别检索,如果传入的参数是空的,此时查询出的结果很可能是空的,也许我们需要参数为空 时,是查出全部的信息。这是我们可以使用动态sql,增加一个判断,当参数不符合要求的时候,我们可以不去判断此查询条件。
 下文均采用mysql语法和函数(例如字符串链接函数CONCAT

3.1 if标签
 一个很普通的查询:

Xml代码  

[html]  view plain  copy
  1. <!-- 查询学生list,like姓名 -->     
  2. <select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">     
  3.     SELECT * from STUDENT_TBL ST       
  4. WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  5. </select>     


但是此时如果studentName是null或空字符串,此语句很可能报错或查询结果为空。此时我们使用if动态sql语句先进行判断,如果值为null或等于空字符串,我们就不进行此条件的判断。

修改为:

Xml代码  

[html]  view plain  copy
  1. <!-- 查询学生list,like姓名 -->     
  2. <select id=" getStudentListLikeName " parameterType="StudentEntity" resultMap="studentResultMap">     
  3.     SELECT * from STUDENT_TBL ST      
  4.     <if test="studentName!=null and studentName!='' ">     
  5.         WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  6.     </if>     
  7. </select>     



 此时,当studentName的值为null或’’的时候,我们并不进行where条件的判断,所以当studentName值为null或’’值,不附带这个条件,所以查询结果是全部。

 由于参数是Java的实体类,所以我们可以把所有条件都附加上,使用时比较灵活, new一个这样的实体类,我们需要限制那个条件,只需要附上相应的值就会where这个条件,相反不去赋值就可以不在where中判断。


   代码中的where标签,请参考3.2.1.

Xml代码  

[html]  view plain  copy
  1. <!-- 查询学生list,like姓名,=性别、=生日、=班级,使用where,参数entity类型 -->     
  2. <select id="getStudentListWhereEntity" parameterType="StudentEntity" resultMap="studentResultMap">     
  3.     SELECT * from STUDENT_TBL ST      
  4.     <where>     
  5.         <if test="studentName!=null and studentName!='' ">     
  6.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  7.         </if>     
  8.         <if test="studentSex!= null and studentSex!= '' ">     
  9.             AND ST.STUDENT_SEX = #{studentSex}      
  10.         </if>     
  11.         <if test="studentBirthday!=null">     
  12.             AND ST.STUDENT_BIRTHDAY = #{studentBirthday}      
  13.         </if>     
  14.         <if test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">     
  15.             AND ST.CLASS_ID = #{classEntity.classID}      
  16.         </if>     
  17.     </where>     
  18. </select>     



查询,姓名中有‘李’,男,生日在‘1985-05-28’,班级在‘20000002’的学生。

Java代码  

[java]  view plain  copy
  1. StudentEntity entity = new StudentEntity();      
  2. entity.setStudentName("李");      
  3. entity.setStudentSex("男");      
  4. entity.setStudentBirthday(StringUtil.parse("1985-05-28"));      
  5. entity.setClassEntity(classMapper.getClassByID("20000002"));      
  6. List<StudentEntity> studentList = studentMapper.getStudentListWhereEntity(entity);      
  7. for( StudentEntity entityTemp : studentList){      
  8.     System.out.println(entityTemp.toString());      
  9. }     



3.2 where、set、trim标签

3.2.1 where
当if标签较多时,这样的组合可能会导致错误。例如,like姓名,等于指定性别等:

Xml代码  

[html]  view plain  copy
  1. <!-- 查询学生list,like姓名,=性别 -->     
  2. <select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">     
  3.     SELECT * from STUDENT_TBL ST      
  4.         WHERE      
  5.         <if test="studentName!=null and studentName!='' ">     
  6.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  7.         </if>     
  8.         <if test="studentSex!= null and studentSex!= '' ">     
  9.             AND ST.STUDENT_SEX = #{studentSex}      
  10.         </if>     
  11. </select>     



 如果上面例子,参数studentName为null或’’,则或导致此sql组合成“WHERE AND”之类的关键字多余的错误SQL。
 这时我们可以使用where动态语句来解决。这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。
 上面例子修改为:

Xml代码  

[html]  view plain  copy
  1. <!-- 查询学生list,like姓名,=性别 -->     
  2. <select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">     
  3.     SELECT * from STUDENT_TBL ST      
  4.     <where>     
  5.         <if test="studentName!=null and studentName!='' ">     
  6.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  7.         </if>     
  8.         <if test="studentSex!= null and studentSex!= '' ">     
  9.             AND ST.STUDENT_SEX = #{studentSex}      
  10.         </if>     
  11.     </where>     
  12. </select>     


3.2.2 set
当在update语句中使用if标签时,如果前面的if没有执行,则或导致逗号多余错误。使用set标签可以将动态的配置SET 关键字,和剔除追加到条件末尾的任何不相关的逗号。
没有使用if标签时,如果有一个参数为null,都会导致错误,如下示例:

Xml代码  

[html]  view plain  copy
  1. <!-- 更新学生信息 -->     
  2. <update id="updateStudent" parameterType="StudentEntity">     
  3.     UPDATE STUDENT_TBL      
  4.        SET STUDENT_TBL.STUDENT_NAME = #{studentName},      
  5.            STUDENT_TBL.STUDENT_SEX = #{studentSex},      
  6.            STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},      
  7.            STUDENT_TBL.CLASS_ID = #{classEntity.classID}      
  8.      WHERE STUDENT_TBL.STUDENT_ID = #{studentID};      
  9. </update>     


 使用set+if标签修改后,如果某项为null则不进行更新,而是保持数据库原值。如下示例:

Xml代码  

[html]  view plain  copy
  1. <!-- 更新学生信息 -->     
  2. <update id="updateStudent" parameterType="StudentEntity">     
  3.     UPDATE STUDENT_TBL      
  4.     <set>     
  5.         <if test="studentName!=null and studentName!='' ">     
  6.             STUDENT_TBL.STUDENT_NAME = #{studentName},      
  7.         </if>     
  8.         <if test="studentSex!=null and studentSex!='' ">     
  9.             STUDENT_TBL.STUDENT_SEX = #{studentSex},      
  10.         </if>     
  11.         <if test="studentBirthday!=null ">     
  12.             STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},      
  13.         </if>     
  14.         <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' ">     
  15.             STUDENT_TBL.CLASS_ID = #{classEntity.classID}      
  16.         </if>     
  17.     </set>     
  18.     WHERE STUDENT_TBL.STUDENT_ID = #{studentID};      
  19. </update>     


3.2.3 trim
 trim是更灵活的去处多余关键字的标签,他可以实践where和set的效果。


 where例子的等效trim语句:

Xml代码  

[html]  view plain  copy
  1. <!-- 查询学生list,like姓名,=性别 -->     
  2. <select id="getStudentListWhere" parameterType="StudentEntity" resultMap="studentResultMap">     
  3.     SELECT * from STUDENT_TBL ST      
  4.     <trim prefix="WHERE" prefixOverrides="AND|OR">     
  5.         <if test="studentName!=null and studentName!='' ">     
  6.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  7.         </if>     
  8.         <if test="studentSex!= null and studentSex!= '' ">     
  9.             AND ST.STUDENT_SEX = #{studentSex}      
  10.         </if>     
  11.     </trim>     
  12. </select>     


set例子的等效trim语句:

Xml代码  

[html]  view plain  copy
  1. <!-- 更新学生信息 -->     
  2. <update id="updateStudent" parameterType="StudentEntity">     
  3.     UPDATE STUDENT_TBL      
  4.     <trim prefix="SET" suffixOverrides=",">     
  5.         <if test="studentName!=null and studentName!='' ">     
  6.             STUDENT_TBL.STUDENT_NAME = #{studentName},      
  7.         </if>     
  8.         <if test="studentSex!=null and studentSex!='' ">     
  9.             STUDENT_TBL.STUDENT_SEX = #{studentSex},      
  10.         </if>     
  11.         <if test="studentBirthday!=null ">     
  12.             STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},      
  13.         </if>     
  14.         <if test="classEntity!=null and classEntity.classID!=null and classEntity.classID!='' ">     
  15.             STUDENT_TBL.CLASS_ID = #{classEntity.classID}      
  16.         </if>     
  17.     </trim>     
  18.     WHERE STUDENT_TBL.STUDENT_ID = #{studentID};      
  19. </update>     


3.3 choose (when, otherwise)
         有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。MyBatis提供了choose 元素,按顺序判断when中的条件出否成立,如果有一个成立,则choose结束。当choose中所有when的条件都不满则时,则执行 otherwise中的sql。类似于Java 的switch 语句,choose为switch,when为case,otherwise则为default。
         if是与(and)的关系,而choose是或(or)的关系。


         例如下面例子,同样把所有可以限制的条件都写上,方面使用。选择条件顺序,when标签的从上到下的书写顺序:

Xml代码  

[html]  view plain  copy
  1. <!-- 查询学生list,like姓名、或=性别、或=生日、或=班级,使用choose -->     
  2. <select id="getStudentListChooseEntity" parameterType="StudentEntity" resultMap="studentResultMap">     
  3.     SELECT * from STUDENT_TBL ST      
  4.     <where>     
  5.         <choose>     
  6.             <when test="studentName!=null and studentName!='' ">     
  7.                     ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')      
  8.             </when>     
  9.             <when test="studentSex!= null and studentSex!= '' ">     
  10.                     AND ST.STUDENT_SEX = #{studentSex}      
  11.             </when>     
  12.             <when test="studentBirthday!=null">     
  13.                 AND ST.STUDENT_BIRTHDAY = #{studentBirthday}      
  14.             </when>     
  15.             <when test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">     
  16.                 AND ST.CLASS_ID = #{classEntity.classID}      
  17.             </when>     
  18.             <otherwise>     
  19.                       
  20.             </otherwise>     
  21.         </choose>     
  22.     </where>     
  23. </select>     


3.4 foreach
对于动态SQL 非常必须的,主是要迭代一个集合,通常是用于IN 条件。
List 实例将使用“list”做为键,数组实例以“array” 做为键。

 

 3.4.1参数为list实例的写法:
SQL写法:

Xml代码  

[html]  view plain  copy
  1. <select id="getStudentListByClassIDs" resultMap="studentResultMap">     
  2.     SELECT * FROM STUDENT_TBL ST      
  3.      WHERE ST.CLASS_ID IN       
  4.      <foreach collection="list" item="classList"  open="(" separator="," close=")">     
  5.         #{classList}      
  6.      </foreach>         
  7. </select>     


接口的方法声明:

[java]  view plain  copy
  1. public List<StudentEntity> getStudentListByClassIDs(List<String> classList);     
  2. public List<StudentEntity> getStudentListByClassIDs(List<String> classList); 测试代码,查询学生中,在2000000220000003这两个班级的学生:  

[java]  view plain  copy
  1. List<String> classList = new ArrayList<String>();      
  2. classList.add("20000002");      
  3. classList.add("20000003");      
  4.      
  5. List<StudentEntity> studentList = studentMapper.getStudentListByClassIDs(classList);      
  6. for( StudentEntity entityTemp : studentList){      
  7.     System.out.println(entityTemp.toString());      
  8. }     
  9. List<String> classList = new ArrayList<String>();  
  10. classList.add("20000002");  
  11. classList.add("20000003");  
  12. List<StudentEntity> studentList = studentMapper.getStudentListByClassIDs(classList);  
  13. for( StudentEntity entityTemp : studentList){  
  14.  System.out.println(entityTemp.toString());  
  15. }  


 3.4.2参数为Array实例的写法:
SQL语句:

[html]  view plain  copy
  1. <select id="getStudentListByClassIDs" resultMap="studentResultMap">     
  2.     SELECT * FROM STUDENT_TBL ST      
  3.      WHERE ST.CLASS_ID IN       
  4.      <foreach collection="array" item="ids"  open="(" separator="," close=")">     
  5.         #{ids}      
  6.      </foreach>     
  7. </select>     


 接口的方法声明:

[java]  view plain  copy
  1. public List<StudentEntity> getStudentListByClassIDs(String[] ids);     
  2. public List<StudentEntity> getStudentListByClassIDs(String[] ids);测试代码,查询学生中,在2000000220000003这两个班级的学生:  

[java]  view plain  copy
  1. String[] ids = new String[2];      
  2. ids[0] = "20000002";      
  3. ids[1] = "20000003";      
  4. List<StudentEntity> studentList = studentMapper.getStudentListByClassIDs(ids);      
  5. for( StudentEntity entityTemp : studentList){      
  6.     System.out.println(entityTemp.toString());      
  7. }   

------------------------------------------------------------------------------------------------------------------------------------

choose (when, otherwise)标签

有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。而使用if标签时,只要test中的表达式为 true,就会执行 if 标签中的条件。MyBatis 提供了 choose 元素。if标签是与(and)的关系,而 choose 是或(or)的关系。

choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。

例如下面例子,同样把所有可以限制的条件都写上,方面使用。choose会从上到下选择一个when标签的test为true的sql执行。安全考虑,我们使用where将choose包起来,放置关键字多于错误。

<!--  choose(判断参数) - 按顺序将实体类 User 第一个不为空的属性作为:where条件 -->  
<select id="getUserList_choose" resultMap="resultMap_user" parameterType="com.yiibai.pojo.User">  
    SELECT *  
      FROM User u   
    <where>  
        <choose>  
            <when test="username !=null ">  
                u.username LIKE CONCAT(CONCAT('%', #{username, jdbcType=VARCHAR}),'%')  
            </when >  
            <when test="sex != null and sex != '' ">  
                AND u.sex = #{sex, jdbcType=INTEGER}  
            </when >  
            <when test="birthday != null ">  
                AND u.birthday = #{birthday, jdbcType=DATE}  
            </when >  
            <otherwise>  
            </otherwise>  
        </choose>  
    </where>    
</select>  

choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中 的 choose 很类似。

<select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">
        select * from t_blog where 1 = 1 
        <choose>
            <when test="title != null">
                and title = #{title}
            </when>
            <when test="content != null">
                and content = #{content}
            </when>
            <otherwise>
                and owner = "owner1"
            </otherwise>
        </choose>
    </select>

when元素表示当 when 中的条件满足的时候就输出其中的内容,跟 JAVA 中的 switch 效果差不多的是按照条件的顺序,当 when 中有条件满足的时候,就会跳出 choose,即所有的 when 和 otherwise 条件中,只有一个会输出,当所有的我很条件都不满足的时候就输出 otherwise 中的内容。所以上述语句的意思非常简单, 当 title!=null 的时候就输出 and titlte = #{title},不再往下判断条件,当title为空且 content!=null 的时候就输出 and content = #{content},当所有条件都不满足的时候就输出 otherwise 中的内容。


selectKey 标签

       在insert语句中,在Oracle经常使用序列、在MySQL中使用函数来自动生成插入表的主键,而且需要方法能返回这个生成主键。使用myBatis的selectKey标签可以实现这个效果。

       下面例子,使用mysql数据库自定义函数nextval('student'),用来生成一个key,并把他设置到传入的实体类中的studentId属性上。所以在执行完此方法后,边可以通过这个实体类获取生成的key。

Xml代码   收藏代码
  1. <!-- 插入学生 自动主键-->  
  2. <insert id="createStudentAutoKey" parameterType="liming.student.manager.data.model.StudentEntity" keyProperty="studentId">  
  3.     <selectKey keyProperty="studentId" resultType="String" order="BEFORE">  
  4.         select nextval('student')  
  5.     </selectKey>  
  6.     INSERT INTO STUDENT_TBL(STUDENT_ID,  
  7.                             STUDENT_NAME,  
  8.                             STUDENT_SEX,  
  9.                             STUDENT_BIRTHDAY,  
  10.                             STUDENT_PHOTO,  
  11.                             CLASS_ID,  
  12.                             PLACE_ID)  
  13.     VALUES (#{studentId},  
  14.             #{studentName},  
  15.             #{studentSex},  
  16.             #{studentBirthday},  
  17.             #{studentPhoto, javaType=byte[], jdbcType=BLOBtypeHandler=org.apache.ibatis.type.BlobTypeHandler},  
  18.             #{classId},  
  19.             #{placeId})  
  20. </insert>  
 

 

 

调用接口方法,和获取自动生成key

Java代码   收藏代码
  1. StudentEntity entity = new StudentEntity();  
  2. entity.setStudentName("黎明你好");  
  3. entity.setStudentSex(1);  
  4. entity.setStudentBirthday(DateUtil.parse("1985-05-28"));  
  5. entity.setClassId("20000001");  
  6. entity.setPlaceId("70000001");  
  7. this.dynamicSqlMapper.createStudentAutoKey(entity);  
  8. System.out.println("新增学生ID: " + entity.getStudentId());  

 

 

selectKey语句属性配置细节:

 

属性描述取值
keyPropertyselectKey 语句生成结果需要设置的属性。
resultType生成结果类型,MyBatis 允许使用基本的数据类型,包括String 、int类型。
order

1:BEFORE,会先选择主键,然后设置keyProperty,再执行insert语句;

2:AFTER,就先运行insert 语句再运行selectKey 语句。

BEFORE

AFTER
statementTypeMyBatis 支持STATEMENT,PREPARED和CALLABLE 的语句形式, 对应Statement,PreparedStatement 和CallableStatement 响应

STATEMENT

PREPARED

CALLABLE

 

 if标签

 

 if标签可用在许多类型的sql语句中,我们以查询为例。首先看一个很普通的查询:

Xml代码   收藏代码
  1. <!-- 查询学生list,like姓名 -->  
  2. <select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">  
  3.     SELECT * from STUDENT_TBL ST   
  4. WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')  
  5. </select>  

 

 

但是此时如果studentName或studentSex为null,此语句很可能报错或查询结果为空。此时我们使用if动态sql语句先进行判断,如果值为null或等于空字符串,我们就不进行此条件的判断,增加灵活性。

参数为实体类StudentEntity。将实体类中所有的属性均进行判断,如果不为空则执行判断条件。

Xml代码   收藏代码
  1. <!-- 2 if(判断参数) - 将实体类不为空的属性作为where条件 -->  
  2. <select id="getStudentList_if" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity">  
  3.     SELECT ST.STUDENT_ID,  
  4.            ST.STUDENT_NAME,  
  5.            ST.STUDENT_SEX,  
  6.            ST.STUDENT_BIRTHDAY,  
  7.            ST.STUDENT_PHOTO,  
  8.            ST.CLASS_ID,  
  9.            ST.PLACE_ID  
  10.       FROM STUDENT_TBL ST   
  11.      WHERE  
  12.     <if test="studentName !=null ">  
  13.         ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
  14.     </if>  
  15.     <if test="studentSex != null and studentSex != '' ">  
  16.         AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
  17.     </if>  
  18.     <if test="studentBirthday != null ">  
  19.         AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
  20.     </if>  
  21.     <if test="classId != null and classId!= '' ">  
  22.         AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
  23.     </if>  
  24.     <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">  
  25.         AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
  26.     </if>  
  27.     <if test="placeId != null and placeId != '' ">  
  28.         AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
  29.     </if>  
  30.     <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">  
  31.         AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
  32.     </if>  
  33.     <if test="studentId != null and studentId != '' ">  
  34.         AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
  35.     </if>   
  36. </select>  
 

 

 

使用时比较灵活, new一个这样的实体类,我们需要限制那个条件,只需要附上相应的值就会where这个条件,相反不去赋值就可以不在where中判断。

Java代码   收藏代码
  1. public void select_test_2_1() {  
  2.     StudentEntity entity = new StudentEntity();  
  3.     entity.setStudentName("");  
  4.     entity.setStudentSex(1);  
  5.     entity.setStudentBirthday(DateUtil.parse("1985-05-28"));  
  6.     entity.setClassId("20000001");  
  7.     //entity.setPlaceId("70000001");  
  8.     List<StudentEntity> list = this.dynamicSqlMapper.getStudentList_if(entity);  
  9.     for (StudentEntity e : list) {  
  10.         System.out.println(e.toString());  
  11.     }  
  12. }  
 

 

 if + where 的条件判断

       当where中的条件使用的if标签较多时,这样的组合可能会导致错误。我们以在3.1中的查询语句为例子,当java代码按如下方法调用时:

Java代码   收藏代码
  1. @Test  
  2. public void select_test_2_1() {  
  3.     StudentEntity entity = new StudentEntity();  
  4.     entity.setStudentName(null);  
  5.     entity.setStudentSex(1);  
  6.     List<StudentEntity> list = this.dynamicSqlMapper.getStudentList_if(entity);  
  7.     for (StudentEntity e : list) {  
  8.         System.out.println(e.toString());  
  9.     }  
  10. }  

 

 

如果上面例子,参数studentName为null,将不会进行STUDENT_NAME列的判断,则会直接导“WHERE AND”关键字多余的错误SQL。

 

这时我们可以使用where动态语句来解决。这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。

上面例子修改为:

Xml代码   收藏代码
  1. <!-- 3 select - where/if(判断参数) - 将实体类不为空的属性作为where条件 -->  
  2. <select id="getStudentList_whereIf" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity">  
  3.     SELECT ST.STUDENT_ID,  
  4.            ST.STUDENT_NAME,  
  5.            ST.STUDENT_SEX,  
  6.            ST.STUDENT_BIRTHDAY,  
  7.            ST.STUDENT_PHOTO,  
  8.            ST.CLASS_ID,  
  9.            ST.PLACE_ID  
  10.       FROM STUDENT_TBL ST   
  11.     <where>  
  12.         <if test="studentName !=null ">  
  13.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
  14.         </if>  
  15.         <if test="studentSex != null and studentSex != '' ">  
  16.             AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
  17.         </if>  
  18.         <if test="studentBirthday != null ">  
  19.             AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
  20.         </if>  
  21.         <if test="classId != null and classId!= '' ">  
  22.             AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
  23.         </if>  
  24.         <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">  
  25.             AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
  26.         </if>  
  27.         <if test="placeId != null and placeId != '' ">  
  28.             AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
  29.         </if>  
  30.         <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">  
  31.             AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
  32.         </if>  
  33.         <if test="studentId != null and studentId != '' ">  
  34.             AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
  35.         </if>  
  36.     </where>    
  37. </select>  
 

 

 

 if + set 的更新语句

当update语句中没有使用if标签时,如果有一个参数为null,都会导致错误。

当在update语句中使用if标签时,如果前面的if没有执行,则或导致逗号多余错误。使用set标签可以将动态的配置SET 关键字,和剔除追加到条件末尾的任何不相关的逗号。

 

       使用if+set标签修改后,如果某项为null则不进行更新,而是保持数据库原值。如下示例:

Xml代码   收藏代码
  1. <!-- 4 if/set(判断参数) - 将实体类不为空的属性更新 -->  
  2. <update id="updateStudent_if_set" parameterType="liming.student.manager.data.model.StudentEntity">  
  3.     UPDATE STUDENT_TBL  
  4.     <set>  
  5.         <if test="studentName != null and studentName != '' ">  
  6.             STUDENT_TBL.STUDENT_NAME = #{studentName},  
  7.         </if>  
  8.         <if test="studentSex != null and studentSex != '' ">  
  9.             STUDENT_TBL.STUDENT_SEX = #{studentSex},  
  10.         </if>  
  11.         <if test="studentBirthday != null ">  
  12.             STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},  
  13.         </if>  
  14.         <if test="studentPhoto != null ">  
  15.             STUDENT_TBL.STUDENT_PHOTO = #{studentPhoto, javaType=byte[], jdbcType=BLOBtypeHandler=org.apache.ibatis.type.BlobTypeHandler},  
  16.         </if>  
  17.         <if test="classId != '' ">  
  18.             STUDENT_TBL.CLASS_ID = #{classId}  
  19.         </if>  
  20.         <if test="placeId != '' ">  
  21.             STUDENT_TBL.PLACE_ID = #{placeId}  
  22.         </if>  
  23.     </set>  
  24.     WHERE STUDENT_TBL.STUDENT_ID = #{studentId};      
  25. </update>  

 

 

 

 if + trim代替where/set标签

       trim是更灵活的去处多余关键字的标签,他可以实践where和set的效果。

 

3.5.1trim代替where

 

Xml代码   收藏代码
  1. <!-- 5.1 if/trim代替where(判断参数) - 将实体类不为空的属性作为where条件 -->  
  2. <select id="getStudentList_if_trim" resultMap="resultMap_studentEntity">  
  3.     SELECT ST.STUDENT_ID,  
  4.            ST.STUDENT_NAME,  
  5.            ST.STUDENT_SEX,  
  6.            ST.STUDENT_BIRTHDAY,  
  7.            ST.STUDENT_PHOTO,  
  8.            ST.CLASS_ID,  
  9.            ST.PLACE_ID  
  10.       FROM STUDENT_TBL ST   
  11.     <trim prefix="WHERE" prefixOverrides="AND|OR">  
  12.         <if test="studentName !=null ">  
  13.             ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
  14.         </if>  
  15.         <if test="studentSex != null and studentSex != '' ">  
  16.             AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
  17.         </if>  
  18.         <if test="studentBirthday != null ">  
  19.             AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
  20.         </if>  
  21.         <if test="classId != null and classId!= '' ">  
  22.             AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
  23.         </if>  
  24.         <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">  
  25.             AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
  26.         </if>  
  27.         <if test="placeId != null and placeId != '' ">  
  28.             AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
  29.         </if>  
  30.         <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">  
  31.             AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
  32.         </if>  
  33.         <if test="studentId != null and studentId != '' ">  
  34.             AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
  35.         </if>  
  36.     </trim>     
  37. </select>  
 

 

 trim代替set

 

Xml代码   收藏代码
  1. <!-- 5.2 if/trim代替set(判断参数) - 将实体类不为空的属性更新 -->  
  2. <update id="updateStudent_if_trim" parameterType="liming.student.manager.data.model.StudentEntity">  
  3.     UPDATE STUDENT_TBL  
  4.     <trim prefix="SET" suffixOverrides=",">  
  5.         <if test="studentName != null and studentName != '' ">  
  6.             STUDENT_TBL.STUDENT_NAME = #{studentName},  
  7.         </if>  
  8.         <if test="studentSex != null and studentSex != '' ">  
  9.             STUDENT_TBL.STUDENT_SEX = #{studentSex},  
  10.         </if>  
  11.         <if test="studentBirthday != null ">  
  12.             STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},  
  13.         </if>  
  14.         <if test="studentPhoto != null ">  
  15.             STUDENT_TBL.STUDENT_PHOTO = #{studentPhoto, javaType=byte[], jdbcType=BLOBtypeHandler=org.apache.ibatis.type.BlobTypeHandler},  
  16.         </if>  
  17.         <if test="classId != '' ">  
  18.             STUDENT_TBL.CLASS_ID = #{classId},  
  19.         </if>  
  20.         <if test="placeId != '' ">  
  21.             STUDENT_TBL.PLACE_ID = #{placeId}  
  22.         </if>  
  23.     </trim>  
  24.     WHERE STUDENT_TBL.STUDENT_ID = #{studentId}  
  25. </update>  
 


foreach

对于动态SQL 非常必须的,主是要迭代一个集合,通常是用于IN 条件。List 实例将使用“list”做为键,数组实例以“array” 做为键。

foreach元素是非常强大的,它允许你指定一个集合,声明集合项和索引变量,它们可以用在元素体内。它也允许你指定开放和关闭的字符串,在迭代之间放置分隔符。这个元素是很智能的,它不会偶然地附加多余的分隔符。

注意:你可以传递一个List实例或者数组作为参数对象传给MyBatis。当你这么做的时候,MyBatis会自动将它包装在一个Map中,用名称在作为键。List实例将会以“list”作为键,而数组实例将会以“array”作为键。

这个部分是对关于XML配置文件和XML映射文件的而讨论的。下一部分将详细讨论Java API,所以你可以得到你已经创建的最有效的映射。

 

 

1参数为array示例的写法

 

接口的方法声明:

Java代码   收藏代码
  1. public List<StudentEntity> getStudentListByClassIds_foreach_array(String[] classIds);  

 

动态SQL语句:

Xml代码   收藏代码
  1. <!— 7.1 foreach(循环array参数) - 作为where中in的条件 -->  
  2. <select id="getStudentListByClassIds_foreach_array" resultMap="resultMap_studentEntity">  
  3.     SELECT ST.STUDENT_ID,  
  4.            ST.STUDENT_NAME,  
  5.            ST.STUDENT_SEX,  
  6.            ST.STUDENT_BIRTHDAY,  
  7.            ST.STUDENT_PHOTO,  
  8.            ST.CLASS_ID,  
  9.            ST.PLACE_ID  
  10.       FROM STUDENT_TBL ST  
  11.       WHERE ST.CLASS_ID IN   
  12.      <foreach collection="array" item="classIds"  open="(" separator="," close=")">  
  13.         #{classIds}  
  14.      </foreach>  
  15. </select>  

 

测试代码,查询学生中,在20000001、20000002这两个班级的学生:

Java代码   收藏代码
  1. @Test  
  2. public void test7_foreach() {  
  3.     String[] classIds = { "20000001""20000002" };  
  4.     List<StudentEntity> list = this.dynamicSqlMapper.getStudentListByClassIds_foreach_array(classIds);  
  5.     for (StudentEntity e : list) {  
  6.         System.out.println(e.toString());  
  7.     }  
  8. <p>}<span style="font-size: 14px; font-weight: bold; white-space: normal;">  </span></p>  


2参数为list示例的写法

接口的方法声明:

Java代码   收藏代码
  1. public List<StudentEntity> getStudentListByClassIds_foreach_list(List<String> classIdList);  

 

动态SQL语句:

Xml代码   收藏代码
  1. <!-- 7.2 foreach(循环List<String>参数) - 作为where中in的条件 -->  
  2. <select id="getStudentListByClassIds_foreach_list" resultMap="resultMap_studentEntity">  
  3.     SELECT ST.STUDENT_ID,  
  4.            ST.STUDENT_NAME,  
  5.            ST.STUDENT_SEX,  
  6.            ST.STUDENT_BIRTHDAY,  
  7.            ST.STUDENT_PHOTO,  
  8.            ST.CLASS_ID,  
  9.            ST.PLACE_ID  
  10.       FROM STUDENT_TBL ST  
  11.       WHERE ST.CLASS_ID IN   
  12.      <foreach collection="list" item="classIdList"  open="(" separator="," close=")">  
  13.         #{classIdList}  
  14.      </foreach>  
  15. </select>  
  

测试代码,查询学生中,在20000001、20000002这两个班级的学生:

Java代码   收藏代码
  1. @Test  
  2. public void test7_2_foreach() {  
  3.     ArrayList<String> classIdList = new ArrayList<String>();  
  4.     classIdList.add("20000001");  
  5.     classIdList.add("20000002");  
  6.     List<StudentEntity> list = this.dynamicSqlMapper.getStudentListByClassIds_foreach_list(classIdList);  
  7.     for (StudentEntity e : list) {  
  8.         System.out.println(e.toString());  
  9.     }  
  10. }  
------------------------------------------------------------------------------------------------------------------------

-----------------------------------------------------------------------------------------------------------------------------------





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值