maybatis 各种零散知识总结(传参,返回值,标签等)

1. MyBatis的传入参数parameterType类型分两种

   1. ①. 基本数据类型:int,string,long,Date;

   1. ②. 复杂数据类型:map (parameterType="java.util.HashMap"

      ③. 如果传参为   数组,List   (parameterType="java.util.ArrayList"   一般用于for each标签   下面将会介绍到)   

像1。这种基本传参类型   我就不说了 。下面简单介绍一下② 

一般遇到传如多个参数的时候   一般会选择会新建个实体 或者  创个map

1.1 实体传参 (假设参数的实体为  User  路径为:com.vanke.Entity.User    传入四个参数  (name,age,sex,idnumber))

            serviceimpl 中 一般用  实体.set  设置属性就可以了

  1. User user=new User();
  2. user.setName('张三');
  3. user.setAge(18);
  4. user.setSex('男');
  5. user.setIdnumber('1888888888');
  6.             

一般 mapper .xml文件配置为

  1. <select id="queryCarMakerList" resultMap="BaseResultMap" parameterType="com.vanke.Entity.User">  
  2.         select  
  3.          *
  4.         from common_car_make cm  
  5.         where 1=1  
  6.         <if test="name!= null">  
  7.             and  cm.name= #{name,jdbcType=DECIMAL}  
  8.         </if>  
  9.         <if test="age!= null">  
  10.             and  cm.name = #{carDeptName,jdbcType=VARCHAR}  
  11.         </if>  
  12.         <if test="sex!= null">  
  13.             and  cm.sex = #{carMakerName,jdbcType=VARCHAR}  
  14.         </if>  
  15.         <if test="idnumber != null" >  
  16.            and  cm.idnumber = #{hotType,jdbcType=number}  
  17.         </if>  
  18.         ORDER BY cm.id  
  19.     </select> 
2. map集合传参( 传入四个参数  (name,age,sex,idnumber)

        serviceimpl 中

  1. Map map=new HashMap();
  2. map.put("name","张三");
  3. map.put("age","18");
  4. map.put("sex","男");
  5. map.put("idnumber","18888888888888");

mapper .xml文件配置为

  1. <select id="queryCarMakerList" resultMap="BaseResultMap" parameterType="map">  
  2.         select  
  3.          *
  4.         from common_car_make cm  
  5.         where 1=1  
  6.         <if test="name!= null">  
  7.             and  cm.name= #{name,jdbcType=DECIMAL}  
  8.         </if>  
  9.         <if test="age!= null">  
  10.             and  cm.name = #{carDeptName,jdbcType=VARCHAR}  
  11.         </if>  
  12.         <if test="sex!= null">  
  13.             and  cm.sex = #{carMakerName,jdbcType=VARCHAR}  
  14.         </if>  
  15.         <if test="idnumber != null" >  
  16.            and  cm.idnumber = #{hotType,jdbcType=number}  
  17.         </if>  
  18.         ORDER BY cm.id  
  19.     </select> 



2.MyBatis的返回参数类型分两种

1.1. resultMap :(自己指定返回的参数 )

  ①  先定义一个<resultMap    id 即为 resultMap 的命名>

<resultMap id="HouseResultMap" type="com.vankeHouse">
    <id property="id" column="id"/>
    <result property="dev_code" column="dev_code"/>
    <result property="dev_name" column="dev_name"/>
    <result property="pro_code" column="pro_code"/>

② 设置返回类型 resultMap=“HouseResultMap”

<select id="getHouserRoom" parameterType="int" resultType="HouseResultMap">
    SELECT <include refid="getHouserR"/> from house where id=#{id}
</select>

③ 当返回类型为 map时 (① 返回结果为String





service:


2. 返回为sum时


*****


原因是,sum() 的结果是作为 java.math.BigDecimal 来处理的, 而他不能直接转换成 java.lang.Integer,所以报错。






1.2. resultType :int,string,long,实体

      如果有的小伙伴要问    要返回 List 怎么办

        1. 如果返回 List<String>   返回类型为 String即可  

        2. 如果返回 List<Entity>  返回类型为   实体  即可  



3  .  mybatis中#和$绑定参数的区别  以及用途

     ①  #()方式能够很大程度防止sql注入。    

     ②  $方式无法防止Sql注入。

默认情况下,使用#{}  格式的语法会导致MyBatis创建预处理语句属性并以它为背景设置安全的值(比如?)。这样做很安全,很迅速也是首选做法,有时你只是想直接在SQL语句中插入一个不改变的字符串。比如,像ORDER BY,你可以这样来使用:
ORDER BY ${columnName}


  1. #{}将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。如:order by #{id},如果传入的值是111,那么解析成sql时的值为order by “111”, 如果传入的值是id,则解析成的sql为order by “id”。    (sql报错

  2. ${}将传入的数据直接显示生成在sql中。如:order by 
    ${id},如果传入的值是111,那么解析成sql时的值为order by 111, 如果传入的值是id,则解析成的sql为order 
    by id。



4.Mybatis中 常用的<if><where><foreach><set><choose>等标签详解

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

       一个很普通的查询:
  1. <!-- 查询学生list,姓名 -->     
  2. <select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">     
  3.     SELECT * from userWHERE  name=#{name}
  4. </select>  

    但是此时如果name是null或空字符串,此语句很可能报错或查询结果为空。此时我们使用if动态sql语句先进行判断,如果值为null或等于空字符串,我们就不进行此条件的判断。
        
   一。<if>标签:
            
      
  1. <select id=" getStudentListLikeName " parameterType="StudentEntity" resultMap="studentResultMap">     
  2.     SELECT * from user
  3.     <if test="name!=null and name!='' ">     
  4.        WHERE  name=#{name}  
  5.     </if>     
  6. </select>   
        
       由于参数是Java的实体类,所以我们可以把所有条件都附加上,使用时比较灵活, new一个这样的实体类,我们需要限制那个条件,只需要附上相应的值就会where这个条件,相反不去赋值就可以不在where中判断。   

二 。<where > <if> 标签组合   (适合多个    if  判断的)
           ①:第一种写法
  1. <!-- 查询学生list,like姓名,=性别、=生日、=班级,使用where,参数entity类型 -->     
  2. <select id="getStudentListWhereEntity" parameterType="StudentEntity" resultMap="studentResultMap">     
  3.     SELECT * from user      
  4.     <where>     
  5.         <if test="name!=null and name!='' ">     
  6.              name=#{name}  
  7.         </if>     
  8.         <if test="Sex!= null and Sex!= '' ">     
  9.             ANDsex= #{Sex}      
  10.         </if>     
  11.         <if test="Birthday!=null and Birthday!=''">     
  12.             AND   Birthday= #{Birthday}      
  13.         </if>         
  14.     </where>     
  15. </select>   
       
   ② 第二种写法   (加个 where 1=1)
  1. <select id="getStudentListWhereEntity" parameterType="StudentEntity" resultMap="studentResultMap">     
  2.     SELECT * from user      
  3.      where 1=1  
  4.         <if test="name!=null and name!='' ">     
  5.            AND  name=#{name}  
  6.         </if>     
  7.         <if test="Sex!= null and Sex!= '' ">     
  8.             AND sex= #{Sex}      
  9.         </if>     
  10.         <if test="Birthday!=null and Birthday!=''">     
  11.             AND   Birthday= #{Birthday}      
  12.         </if>             
  13. </select>   

  
   
 三. <set>  <if> 标签组合  (一般用于更新语句)
      
         一个常见的更新代码:( 没有使用if标签时,如果有一个参数为null,都会导致错误
[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则不进行更新,而是保持数据库原值。

  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>  


四。<tirm>标签      ( trim是更灵活的去处多余关键字的标签,他可以实践where和set的效果
               
      where例子的等效trim语句:
  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语句:
       
  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>     


* 五。 <choose >(when, otherwise)   标签
       

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

    

      案例 1:  

  1. <!-- 根据usertype  决定执行哪条sql 语句>     
  2. <select id="getStudentListChooseEntity" parameterType="StudentEntity" resultMap="studentResultMap">        
  3.     <where>     
  4.         <choose>     
  5.             <when test="usertype == 1">     
  6.                  select * from user where usertype=1    
  7.             </when>     
  8.             <when test="usertype == 2 ">     
  9.                   select * from user where usertype=2    
  10.             </when>     
  11.             <when test="usertype == 3">     
  12.                   select * from user where usertype=3   
  13.             </when>     
  14.             <when test="usertype == 4 ">     
  15.                  select * from user where usertype=4   
  16.             </when>     
  17.             <otherwise>     
  18.                       
  19.             </otherwise>     
  20.         </choose>     
  21.     </where>     
  22. </select>     

   案例  2:

  1. <!-- 根据usertype     决定按照什么分组><select id="getStudentListChooseEntity" parameterType="StudentEntity" resultMap="studentResultMap">     
  2.     SELECT * from STUDENT_TBL ST      
  3.     <where>     
  4.         <choose>     
  5.             <when test="usertype == 1">     
  6.                    group by age
  7.             </when>     
  8.             <when test="usertype == 2">     
  9.                   group by  name      
  10.             </when>     
  11.             <when test=""usertype == 3">     
  12.                   group by  sex     
  13.             </when>         
  14.             <otherwise>     
  15.                       
  16.             </otherwise>     
  17.         </choose>     
  18.     </where>     
  19. </select>  


六。 <foreach>   标签  (对于动态SQL 非常必须的,主是要迭代一个集合,通常是用于IN 条件。

List 实例将使用“list”做为键,数组实例以“array” 做为键。

    ①    当传入list的时候

    一。Dao接口 代码写法

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

   二。 java代码  主要是往  list  里放点数据

  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. }  
  
 三。mapper 

  1. <select id="getStudentListByClassIDs" resultMap="studentResultMap">     
  2.     SELECT * FROM STUDENT_TBL ST      
  3.      WHERE ST.CLASS_ID IN       
  4.      <foreach collection="list" item="classList"  index="index"   open="(" separator="," close=")">     
  5.         #{classList}      
  6.      </foreach>         
  7. </select>  
 单独传入list时,foreach中的collection必须是list,不不管变量的具体名称是什么。比如这里变量名为idList,
 collection却是是list。  

      ②    当传入  数组  的时候

   一。Dao接口 代码写法

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

   二。 java代码  主要是往   数组  里放点数据

  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());      

   三。 mapper

   

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

   单独传入数组时,foreach中的collection必须是array,不不管变量的具体名称是什么。比如这里变量名为ids,
    collection却是是array

  ③  当传入多个list的时候  

   Dao里面的写法:

public List<HistorySelect> findAll(@Param("list1")List<Integer> zphids,@Param("list2")List<String> zphbatchNums);

  mapper:


       

七.  case when 用法



 





    
      
      
             





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值