关于java:10-种超好用的-MyBatis-写法同事都说好用

25次阅读

共计 12595 个字符,预计需要花费 32 分钟才能阅读完成。

作者:smile_lg \
起源:blog.csdn.net/smile_lg/article/details/71215619

用来循环容器的标签 forEach, 查看例子

foreach 元素的属性次要有 item,index,collection,open,separator,close。

  • item:汇合中元素迭代时的别名,
  • index:汇合中元素迭代时的索引
  • open:常用语 where 语句中,示意以什么开始,比方以 '(‘ 开始
  • separator:示意在每次进行迭代时的分隔符,
  • close 常用语 where 语句中,示意以什么完结,

在应用 foreach 的时候最要害的也是最容易出错的就是 collection 属性,该属性是必须指定的,然而在不同状况下,该属性的值是不一样的,次要有一下 3 种状况:

  • 如果传入的是单参数且参数类型是一个 List 的时候,collection 属性值为 list .
  • 如果传入的是单参数且参数类型是一个 array 数组的时候,collection 的属性值为 array .
  • 如果传入的参数是多个的时候,咱们就须要把它们封装成一个 Map 了,当然单参数也能够封装成 map,实际上如果你在传入参数的时候,在 MyBatis 外面也是会把它封装成一个 Map 的,map 的 key 就是参数名,所以这个时候 collection 属性值就是传入的 List 或 array 对象在本人封装的 map 外面的 key.

针对最初一条,咱们来看一下官网说法:

留神 你能够将一个 List 实例或者数组作为参数对象传给 MyBatis,当你这么做的时候,MyBatis 会主动将它包装在一个 Map 中并以名称为键。List 实例将会以“list”作为键,而数组实例的键将是“array”。

所以,不论是多参数还是单参数的 list,array 类型,都能够封装为 map 进行传递。如果传递的是一个 List,则 mybatis 会封装为一个 list 为 key,list 值为 object 的 map,如果是 array,则封装成一个 array 为 key,array 的值为 object 的 map,如果本人封装呢,则 colloection 里放的是本人封装的 map 里的 key 值

//mapper 中咱们要为这个办法传递的是一个容器, 将容器中的元素一个一个的
// 拼接到 xml 的办法中就要应用这个 forEach 这个标签了
public List<Entity> queryById(List<String> userids);

// 对应的 xml 中如下
  <select id="queryById" resultMap="BaseReslutMap" >
      select * FROM entity
      where id in 
      <foreach collection="userids" item="userid" index="index" open="(" separator="," close=")">
              #{userid}
      </foreach>
  </select>

concat 含糊查问

// 比如说咱们想要进行条件查问, 然而几个条件不是每次都要应用, 那么咱们就能够
// 通过判断是否拼接到 sql 中
  <select id="queryById" resultMap="BascResultMap" parameterType="entity">
    SELECT *  from entity
    <where>
        <if test="name!=null">
            name like concat('%',concat(#{name},'%'))
        </if>
    </where>
  </select>

举荐一个开源收费的 Spring Boot 最全教程:

https://github.com/javastacks/spring-boot-best-practice

choose (when, otherwise)标签

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> 

selectKey 标签

在 insert 语句中,在 Oracle 常常应用序列、在 MySQL 中应用函数来主动生成插入表的主键,而且须要办法能返回这个生成主键。应用 myBatis 的 selectKey 标签能够实现这个成果。

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

<!-- 插入学生 主动主键 -->  
<insert id="createStudentAutoKey" parameterType="liming.student.manager.data.model.StudentEntity" keyProperty="studentId">  
    <selectKey keyProperty="studentId" resultType="String" order="BEFORE">  
        select nextval('student')  
    </selectKey>  
    INSERT INTO STUDENT_TBL(STUDENT_ID,  
                            STUDENT_NAME,  
                            STUDENT_SEX,  
                            STUDENT_BIRTHDAY,  
                            STUDENT_PHOTO,  
                            CLASS_ID,  
                            PLACE_ID)  
    VALUES (#{studentId},  
            #{studentName},  
            #{studentSex},  
            #{studentBirthday},  
            #{studentPhoto, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler},  
            #{classId},  
            #{placeId})  
</insert>  

调用接口办法,和获取主动生成 key

StudentEntity entity = new StudentEntity();  
entity.setStudentName("拂晓你好");  
entity.setStudentSex(1);  
entity.setStudentBirthday(DateUtil.parse("1985-05-28"));  
entity.setClassId("20000001");  
entity.setPlaceId("70000001");  
this.dynamicSqlMapper.createStudentAutoKey(entity);  
System.out.println("新增学生 ID:" + entity.getStudentId());  

if 标签

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

<!-- 查问学生 list,like 姓名 -->  
<select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">  
    SELECT * from STUDENT_TBL ST   
WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')  
</select>  

然而此时如果 studentName 为 null,此语句很可能报错或查问后果为空。此时咱们应用 if 动静 sql 语句先进行判断,如果值为 null 或等于空字符串,咱们就不进行此条件的判断,减少灵活性。

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

<!-- 2 if(判断参数) - 将实体类不为空的属性作为 where 条件 -->  
<select id="getStudentList_if" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity">  
    SELECT ST.STUDENT_ID,  
           ST.STUDENT_NAME,  
           ST.STUDENT_SEX,  
           ST.STUDENT_BIRTHDAY,  
           ST.STUDENT_PHOTO,  
           ST.CLASS_ID,  
           ST.PLACE_ID  
      FROM STUDENT_TBL ST   
     WHERE  
    <if test="studentName !=null">  
        ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
    </if>  
    <if test="studentSex != null and studentSex !='' ">  
        AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
    </if>  
    <if test="studentBirthday != null">  
        AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
    </if>  
    <if test="classId != null and classId!='' ">  
        AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
    </if>  
    <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">  
        AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
    </if>  
    <if test="placeId != null and placeId !='' ">  
        AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
    </if>  
    <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId !='' ">  
        AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
    </if>  
    <if test="studentId != null and studentId !='' ">  
        AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
    </if>   
</select> 

应用时比拟灵便,new 一个这样的实体类,咱们须要限度那个条件,只须要附上相应的值就会 where 这个条件,相同不去赋值就能够不在 where 中判断。

public void select_test_2_1() {StudentEntity entity = new StudentEntity();  
    entity.setStudentName("");  
    entity.setStudentSex(1);  
    entity.setStudentBirthday(DateUtil.parse("1985-05-28"));  
    entity.setClassId("20000001");  
    //entity.setPlaceId("70000001");  
    List<StudentEntity> list = this.dynamicSqlMapper.getStudentList_if(entity);  
    for (StudentEntity e : list) {System.out.println(e.toString());  
    }  
}

if + where 的条件判断

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

@Test  
public void select_test_2_1() {StudentEntity entity = new StudentEntity();  
    entity.setStudentName(null);  
    entity.setStudentSex(1);  
    List<StudentEntity> list = this.dynamicSqlMapper.getStudentList_if(entity);  
    for (StudentEntity e : list) {System.out.println(e.toString());  
    }  
} 

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

这时咱们能够应用 where 动静语句来解决。这个“where”标签会晓得如果它蕴含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以 AND 或 OR 结尾的,则它会剔除掉。

下面例子批改为:

<!-- 3 select - where/if(判断参数) - 将实体类不为空的属性作为 where 条件 -->  
<select id="getStudentList_whereIf" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity">  
    SELECT ST.STUDENT_ID,  
           ST.STUDENT_NAME,  
           ST.STUDENT_SEX,  
           ST.STUDENT_BIRTHDAY,  
           ST.STUDENT_PHOTO,  
           ST.CLASS_ID,  
           ST.PLACE_ID  
      FROM STUDENT_TBL ST   
    <where>  
        <if test="studentName !=null">  
            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
        </if>  
        <if test="studentSex != null and studentSex !='' ">  
            AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
        </if>  
        <if test="studentBirthday != null">  
            AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
        </if>  
        <if test="classId != null and classId!='' ">  
            AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
        </if>  
        <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">  
            AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
        </if>  
        <if test="placeId != null and placeId !='' ">  
            AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
        </if>  
        <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId !='' ">  
            AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
        </if>  
        <if test="studentId != null and studentId !='' ">  
            AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
        </if>  
    </where>    
</select>  

if + set 实现批改语句

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

当在 update 语句中应用 if 标签时,如果后面的 if 没有执行,则或导致逗号多余谬误。应用 set 标签能够将动静的配置 SET 关键字,和剔除追加到条件开端的任何不相干的逗号。应用 if+set 标签批改后,如果某项为 null 则不进行更新,而是放弃数据库原值。

如下示例:

<!-- 4 if/set(判断参数) - 将实体类不为空的属性更新 -->  
<update id="updateStudent_if_set" parameterType="liming.student.manager.data.model.StudentEntity">  
    UPDATE STUDENT_TBL  
    <set>  
        <if test="studentName != null and studentName !='' ">  
            STUDENT_TBL.STUDENT_NAME = #{studentName},  
        </if>  
        <if test="studentSex != null and studentSex !='' ">  
            STUDENT_TBL.STUDENT_SEX = #{studentSex},  
        </if>  
        <if test="studentBirthday != null">  
            STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},  
        </if>  
        <if test="studentPhoto != null">  
            STUDENT_TBL.STUDENT_PHOTO = #{studentPhoto, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler},  
        </if>  
        <if test="classId !='' ">  
            STUDENT_TBL.CLASS_ID = #{classId}  
        </if>  
        <if test="placeId !='' ">  
            STUDENT_TBL.PLACE_ID = #{placeId}  
        </if>  
    </set>  
    WHERE STUDENT_TBL.STUDENT_ID = #{studentId};      
</update> 

if + trim 代替 where/set 标签

trim 是更灵便的去处多余关键字的标签,他能够实际 where 和 set 的成果。

trim 代替 where

<!-- 5.1if/trim 代替 where(判断参数) - 将实体类不为空的属性作为 where 条件 -->  
<select id="getStudentList_if_trim" resultMap="resultMap_studentEntity">  
    SELECT ST.STUDENT_ID,  
           ST.STUDENT_NAME,  
           ST.STUDENT_SEX,  
           ST.STUDENT_BIRTHDAY,  
           ST.STUDENT_PHOTO,  
           ST.CLASS_ID,  
           ST.PLACE_ID  
      FROM STUDENT_TBL ST   
    <trim prefix="WHERE" prefixOverrides="AND|OR">  
        <if test="studentName !=null">  
            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
        </if>  
        <if test="studentSex != null and studentSex !='' ">  
            AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
        </if>  
        <if test="studentBirthday != null">  
            AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
        </if>  
        <if test="classId != null and classId!='' ">  
            AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
        </if>  
        <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">  
            AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
        </if>  
        <if test="placeId != null and placeId !='' ">  
            AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
        </if>  
        <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId !='' ">  
            AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
        </if>  
        <if test="studentId != null and studentId !='' ">  
            AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
        </if>  
    </trim>     
</select> 

trim 代替 set

<!-- 5.2 if/trim 代替 set(判断参数) - 将实体类不为空的属性更新 -->  
<update id="updateStudent_if_trim" parameterType="liming.student.manager.data.model.StudentEntity">  
    UPDATE STUDENT_TBL  
    <trim prefix="SET" suffixOverrides=",">  
        <if test="studentName != null and studentName !='' ">  
            STUDENT_TBL.STUDENT_NAME = #{studentName},  
        </if>  
        <if test="studentSex != null and studentSex !='' ">  
            STUDENT_TBL.STUDENT_SEX = #{studentSex},  
        </if>  
        <if test="studentBirthday != null">  
            STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday},  
        </if>  
        <if test="studentPhoto != null">  
            STUDENT_TBL.STUDENT_PHOTO = #{studentPhoto, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler},  
        </if>  
        <if test="classId !='' ">  
            STUDENT_TBL.CLASS_ID = #{classId},  
        </if>  
        <if test="placeId !='' ">  
            STUDENT_TBL.PLACE_ID = #{placeId}  
        </if>  
    </trim>  
    WHERE STUDENT_TBL.STUDENT_ID = #{studentId}  
</update>

foreach

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

foreach 元素是十分弱小的,它容许你指定一个汇合,申明汇合项和索引变量,它们能够用在元素体内。它也容许你指定凋谢和敞开的字符串,在迭代之间搁置分隔符。这个元素是很智能的,它不会偶尔地附加多余的分隔符。

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

这个局部是对对于 XML 配置文件和 XML 映射文件的而探讨的。下一部分将具体探讨 Java API,所以你能够失去你曾经创立的最无效的映射。

1. 参数为 array 示例的写法

接口的办法申明:

public List<StudentEntity> getStudentListByClassIds_foreach_array(String[] classIds);  

动静 SQL 语句:

<!-- 7.1 foreach(循环 array 参数) - 作为 where 中 in 的条件 -->  
<select id="getStudentListByClassIds_foreach_array" resultMap="resultMap_studentEntity">  
    SELECT ST.STUDENT_ID,  
           ST.STUDENT_NAME,  
           ST.STUDENT_SEX,  
           ST.STUDENT_BIRTHDAY,  
           ST.STUDENT_PHOTO,  
           ST.CLASS_ID,  
           ST.PLACE_ID  
      FROM STUDENT_TBL ST  
      WHERE ST.CLASS_ID IN   
     <foreach collection="array" item="classIds"  open="(" separator="," close=")">  
        #{classIds}  
     </foreach>  
</select> 

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

@Test  
public void test7_foreach() {String[] classIds = {"20000001", "20000002"};  
    List<StudentEntity> list = this.dynamicSqlMapper.getStudentListByClassIds_foreach_array(classIds);  
    for (StudentEntity e : list) {System.out.println(e.toString());  
    }  
}

2. 参数为 list 示例的写法

接口的办法申明:

public List<StudentEntity> getStudentListByClassIds_foreach_list(List<String> classIdList); 

动静 SQL 语句:

<!-- 7.2 foreach(循环 List<String> 参数) - 作为 where 中 in 的条件 -->  
<select id="getStudentListByClassIds_foreach_list" resultMap="resultMap_studentEntity">  
    SELECT ST.STUDENT_ID,  
           ST.STUDENT_NAME,  
           ST.STUDENT_SEX,  
           ST.STUDENT_BIRTHDAY,  
           ST.STUDENT_PHOTO,  
           ST.CLASS_ID,  
           ST.PLACE_ID  
      FROM STUDENT_TBL ST  
      WHERE ST.CLASS_ID IN   
     <foreach collection="list" item="classIdList"  open="(" separator="," close=")">  
        #{classIdList}  
     </foreach>  
</select>

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

@Test  
public void test7_2_foreach() {ArrayList<String> classIdList = new ArrayList<String>();  
    classIdList.add("20000001");  
    classIdList.add("20000002");  
    List<StudentEntity> list = this.dynamicSqlMapper.getStudentListByClassIds_foreach_list(classIdList);  
    for (StudentEntity e : list) {System.out.println(e.toString());  
    }  
} 

sql 片段标签<sql>:通过该标签可定义能复用的 sql 语句片段,在执行 sql 语句标签中间接援用即可。这样既能够进步编码效率,还能无效简化代码,进步可读性

须要配置的属性:id=”” >>> 示意须要改 sql 语句片段的惟一标识

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

<!-- 定义 sql 片段 -->  
<sql id="orderAndItem">  
    o.order_id,o.cid,o.address,o.create_date,o.orderitem_id,i.orderitem_id,i.product_id,i.count  
  </sql>  

 <select id="findOrderAndItemsByOid" parameterType="java.lang.String" resultMap="BaseResultMap">  
    select  
<!-- 援用 sql 片段 -->  
    <include refid="orderAndItem" />  
    from ordertable o  
    join orderitem i on o.orderitem_id = i.orderitem_id  
    where o.order_id = #{orderId}  
  </select>  

近期热文举荐:

1.1,000+ 道 Java 面试题及答案整顿(2022 最新版)

2. 劲爆!Java 协程要来了。。。

3.Spring Boot 2.x 教程,太全了!

4. 别再写满屏的爆爆爆炸类了,试试装璜器模式,这才是优雅的形式!!

5.《Java 开发手册(嵩山版)》最新公布,速速下载!

感觉不错,别忘了顺手点赞 + 转发哦!

正文完
 0