Mybatis@Select、foreach

foreach属性

属性描述
item循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details。 具体说明:在list和数组中是其中的对象,在map中是value。 该参数为必选。
collection要做foreach的对象,作为入参时,List<?>对象默认用list代替作为键,数组对象用array代替作为键,Map对象用map代替作为键。 当然在作为入参时可以使用@Param(“keyName”)来设置键,设置keyName后,list,array,map将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子: 如果User有属性List ids。入参是User对象,那么这个collection = “ids” 如果User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = “ids.id” 上面只是举例,具体collection等于什么,就看你想对那个元素做循环。 该参数为必选。
separator元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
openforeach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。该参数可选。
closeforeach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。该参数可选。
index在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。
MapperList<UserRole> selectIdList(List<Long> userList);
XML语句
<select id="selectIdList" parameterType="java.util.List" resultType="com.yuantu.dev.sys.entity.UserRole">
        SELECT id,user_id,role_id FROM sys_user_role
        WHERE user_id IN
        <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
</select>

入参为数组,有@Param 注解

MapperList<UserRole> selectIdList(@Param("userIdList")Long[] userIdList);
XML语句
<select id="selectIdList" parameterType="java.util.List" resultType="com.yuantu.dev.sys.entity.UserRole">
        SELECT id,user_id,role_id FROM sys_user_role
        WHERE user_id IN
        <foreach collection="userIdList" item="userId" open="(" separator="," close=")">
 	        #{userId}
        </foreach> 
</select>

入参为数组,无@Param 注解

MapperList<UserRole> selectIdList(Long[] userIdList);
XML语句
<select id="selectIdList" parameterType="java.util.List" resultType="com.yuantu.dev.sys.entity.UserRole">
        SELECT id,user_id,role_id FROM sys_user_role
        WHERE user_id IN
        <foreach collection="array" item="userId" open="(" separator="," close=")">
 	        #{userId}
        </foreach> 
</select>

@Select注解

常用查询

@Select("select * from web_admins where id = #{id}")
Admin selectAdminById(@Param("id") Integer id);

在@Select中拼写动态SQL语句

对于条件较复杂的情况,不太建议这种方式,在字符串中难免会有很多错误,可读性很差。

@Select("<script>" +
        "SELECT * FROM users WHERE id in \n" +
        "<foreach collection='usedUserIdList' index='index' item='item' open='(' separator=',' close=')'>#{item}</foreach> \n" +
        "AND open_card_order_state = 1" +
        "</script>")
List<Users> selectUsers(@Param("usedUserIdList") List<Integer> usedUserIdList,Page<Users> page);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

问啥啥不会

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值