MyBatis动态SQL之<foreach>用法

目录

一、foreach元素的属性

二、collection属性值的三种情况

三、代码示例

四、相关错误


一、foreach元素的属性

        collection: foreach的对象,作为入参,对象为list、array时,collection属性值分别默认用"list"、"array"代替,Map对象没有默认的属性值。但是,在作为入参时可以使用        

        @Param(“name”)注解来设置自定义collection属性值,设置name后,list、array会失效;

        item: 集合元素迭代时的别名称,该参数为必选项,如果遍历的对象是map,则item为val;

        index: 在list、array中,index为元素的序号索引。但是在Map中,index为遍历元素的key值,该参数为可选项;

        open: 遍历集合时的开始符号,通常与close=")"搭配使用。使用场景IN(),values()时,该参数为可选项;

        separator: 元素之间的分隔符,类比在IN()的时候,separator=",",最终所有遍历的元素将会以设定的(,)逗号符号隔开,该参数为可选项;

        close: 遍历集合时的结束符号,通常与open="("搭配使用,该参数为可选项;

二、collection属性值的三种情况


        1,如果传入的参数类型为list时: collection的默认属性值为list,同样可以使用@Param注解自定义name;

        2,如果传入的参数类型为array时: collection的默认属性值为array,同样可以使用@Param注解自定义name;

       3,如果传入的参数类型为Map时: collection的属性值可为三种情况:1.遍历map.keys;2.遍历map.values;3.遍历map.entrySet();

三、代码示例

        1、properties配置文件:

up.merId=101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116

        2、serviceImpl层:

//读取配置文件
@Value("#{'${up.merId}'.split(',')}")
private List<String> upMerList;




//业务层方法核心
List<OrderInfo> oList = new ArrayList<>();
List<OrderInfo> lList = null;
OrderInfo orI = null;
System.out.println("upMerList:"+upMerList);
try{
       //方法一,对参数list进行遍历,逐个查询,再通过addAll合并所有集合
//     for (String s : upMerList) {
//         orI = new OrderInfo();
//         orI.setSettleDate(yesterDay);
//         orI.setOrderStatus("1");
//         orI.setNy(yesterDay);
//         orI.setMerSysId(s);
//         lList = orderInfoDao.selectOnlyOrderInfo(orI);
//         oList.addAll(lList);
//     }

       //方法二,将list传入SQL,在mapper层处理list参数
       orI = new OrderInfo();
       orI.setSettleDate(yesterDay);
       orI.setOrderStatus("1");
       orI.setNy(yesterDay);
       orI.setUpMerList(upMerList);
       oList = orderInfoDao.selectOnlyOrderInfo(orI);
}catch (Exception e){
       e.printStackTrace();
       logger.info("订单信息日期" + DateUtil.getYesterDay() + ",数据查询失败。");
}

        3、OrderInfo主要参数

//表中包含字段
private String merSysId;

//数据库表中不包含的字段,需要用transient 修饰
private transient List<String> upMerList;

//其他参数及get、set方法在此省略不写

        4、dao层方法

/**
    * 查询订单
	* @param
	* @return
	* @throws Exception
*/
public List<OrderInfo> selectOnlyOrderInfo(OrderInfo orderInfo);

//所有参数都在OrderInfo中,同时参数不需要加其他注解修饰

//若参数不放入OrderInfo中,则使用以下写法
List<OrderInfo> selectOnlyOrderInfo(@param("orderInfo") OrderInfo orderInfo, @param("upMerList") List<String> upMerList)

        5、mapper层

<!-- 查询订单详情 -->
	<select id="selectOnlyOrderInfo" parameterType="com.task.bean.OrderInfo"
			resultMap="orderInfo">
		SELECT
		*
		FROM
		order_info_${ny} o
		<where>
			<if test="orderStatus != null and orderStatus != ''">
					AND o.ORDER_STATUS = #{orderStatus}
			</if>

<!--			该if标签对应上面方法一  -->
<!--			<if test="settleDate != null and settleDate != ''">-->
<!--				AND o.MER_SYS_ID #{merSysId}-->
<!--			</if>-->

<!--			该if标签对应上面方法二  -->
			<if test="upMerList != null">
				AND o.MER_SYS_ID in
 				<foreach collection="upMerList" index="index" item="upMerList" open="(" separator="," close=")">
					#{upMerList}
				</foreach>
			</if>

		</where>
	</select>

运行结果:

upMerList:[101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116]
DEBUG [main] c.t.o.d.O.selectOnlyOrderInfo            : ==>  Preparing: SELECT o.MER_ID, o.MER_SYS_ID, o.ORDER_DATE, o.MER_ORDER_ID, o.USER_NAME, o.CARD_M_NUM, o.SIGN_ORDER_ID, o.ORDER_TIME, o.ORDER_AMT, o.SETTLE_DATE, o.ORDER_STATUS, o.ORDER_CODE, o.ORDER_DESC FROM order_info_20220816 o WHERE o.ORDER_STATUS = ? AND o.MER_SYS_ID in ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? ) 
DEBUG [main] c.t.o.d.O.selectOnlyOrderInfo            : ==> Parameters: 1(String), 101(String), 102(String), 103(String), 104(String), 105(String), 106(String), 107(String), 108(String), 109(String), 110(String), 111(String), 112(String), 113(String), 114(String), 115(String), 116(String)
2022-08-22 11:23:02.072 DEBUG 8128 --- [           main] c.t.o.d.O.selectOnlyOrderInfo            : <==      Total: 771582

四、相关错误

         1、实体类OrderInfo中未添加transient 修饰

Unknown column 'upMerList' in 'field list'

//当出现该错误时,还有其他两种解决办法
//方法一:使用  javax.persistence包下的 @Transient 注解
/*方法二:使用  Mybatis-Plus的注解 @TableField(exist = false)
    * 它用在属性上,表示该属性不为数据库表字段,但又是必须使用的。
    * 使用说明:
    * 若exist = true,则表示该属性为数据库表字段。
    * exist = false,则表示该属性不为数据库表字段。
*/

        2、mapper文件collection="list"时

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'list' in 'class com.task.bean.OrderInfo'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值