作者: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开发手册(嵩山版)》最新公布,速速下载!

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