[关闭]
@hengbao 2018-06-04T03:10:11.000000Z 字数 1024 阅读 1133

如何使用Mybatis 的 foreach标签

Java Mybatis


1.遍历List

1.1.只传入了一个List参数

当我们的Mapper类中只需要传入一个List参数,如下例:

  1. public int updateByIdList(List<Long> myIdList);

在对应的xml文件中,我们只需要标明 list 即可:

  1. <update id="updateByIdList">
  2. UPDATE lalala_table
  3. SET status= 1
  4. <where>
  5. id IN
  6. <foreach collection="list" item="item_id" open="(" separator="," close=")">
  7. ${item_id}
  8. </foreach>
  9. </where>
  10. </update>

1.2.List只是多个参数中的一个参数

当我们需要既传递List,又需要传递其它的参数,我们应该首先封装一个数据类,这样也方便我们对于每一个参数进行注释,我个人不推荐使用HashMap直接传入。例如,我们有下面这样一个参数类:

  1. @Setter
  2. @Getter
  3. public class MyDTO{
  4. private List<Long> myIdList;
  5. private Integer age;
  6. private String name;
  7. }

对应mapper文件中,我们直接传入这个对象,对于xml文件中,我们对应好parameterType与resultType。在使用list的时候,直接写变量的名称即可:

  1. <select id="getSomething" parameterType="com.xxx.MyDTO"
  2. resultType="com.xxx.Student">
  3. SELECT
  4. *
  5. FROM
  6. x
  7. <where>
  8. <if test="null!=myIdList and myIdList.size()>0">
  9. AND x.`id` IN
  10. <foreach collection="myIdList" item="item" open="(" separator="," close=")">
  11. ${item}
  12. </foreach>
  13. </if>
  14. <if test="null!= age">
  15. AND x.`age`= #{age,jdbcType = INTEGER }
  16. </if>
  17. <if test="null!= name">
  18. AND x.`name`= #{name, jdbcType = VARCHAR}
  19. </if>
  20. </where>
  21. </select>

TO BE CONTINUED...

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注