您的位置:首页 > 数据库

mybatis查询sql中in条件使用(foreach)

2018-08-12 22:07 417 查看

foreach属性主要有item,index,collection,open,separator,close。

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

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

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

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

5、close表示以什么结束,

6、collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况: 

a、如果传入的是单参数且参数类型是一个List的时候,collection属性值为list .

b、如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array .

c、如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key.

  1. <select id="findBy" resultMap="RfCustomerMemMap" parameterType="java.util.Map">
  2. SELECT
  3. <include refid="Column"/>
  4. FROM rfl_customer_mem a LEFT JOIN rfl_loan b ON a.member_no = b.loan_member_no
  5. WHERE a.member_no = #{memberNo} AND b.status IN
  6. <foreach collection="status" index="index" item="item" open="(" separator="," close=")">
  7. #{item}
  8. </foreach>
  9. <if test="name != null and name != ''">
  10. AND name = #{name}
  11. </if>
  12. <if test="idNumber != null and idNumber != ''">
  13. AND id_number = #{idNumber}
  14. </if>
  15. <if test="mobileNo != null and mobileNo != ''">
  16. AND mobile_no = #{mobileNo}
  17. </if>
  18. <if test="loanNo != null and loanNo != ''">
  19. AND loan_no = #{loanNo}
  20. </if>
  21. order by a.id DESC
  22. <if test="offset > -1 and rows > -1">
  23. limit #{offset},#{limit}
  24. </if>
  25. </select>

java调用查询sql代码

  1. public List<LoanMerchantMemEntity> findMerchantMemBy(String merchantName, String merchantNo, String socialCreditCode, String loanNo, int offset, int limit) {
  2. List<LoanMerchantMemEntity> list = new ArrayList<LoanMerchantMemEntity>();
  3. Map<String, Object> filter = new HashMap<String, Object>();
  4. filter.put("merchantName", merchantName);
  5. filter.put("socialCreditCode", socialCreditCode);
  6. filter.put("status", statsList());
  7. filter.put("loanNo", loanNo);
  8. filter.put("offset", offset);
  9. filter.put("limit", limit);
  10. filter.put("merchantNo", merchantNo);
  11. try {
  12. List<LoanMerchantMemEntity> row = loanMerchantMemDao.findBy(filter);
  13. } catch (Exception e) {
  14. LOGGER.error(filter, "查询企业会员信息异常", e);
  15. }
  16. return list;
  17. }

[/code]
  1. static List<String> statsList(){
  2. List<String> statusList = new ArrayList<String>();
  3. statusList.add("SUCCESS");
  4. statusList.add("DUE");
  5. statusList.add("OVER");
  6. return statusList;
  7. }
[/code]

其中,map中key为status值类型为list,这种使用场景为第三种,即collection为map中的key值


阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: