记录使用mybatis时的一些代码

发布时间:2024-08-05 17:00:24 浏览数:23

mybatis篇

外部传参英文逗号分隔的字符串

mapper中 projectIds = 1,2,3

xml中

<if test="projectIds != null and projectIds != ''">
     AND project.id IN
     <foreach collection="projectIds.split(',')" item="item" open="(" separator="," close=")">
            #{item}
     </foreach>
</if>

这样生成的sql就是 and project.id in (1,2,3)

外部传参时传入List<String>

java中

List<String> projectIdList = new ArrayList<>();
projectIdList.add("1");
projectIdList.add("2");
projectIdList.add("3");

xml中

            <if test = "projectIdList != null">
                and project.id IN
                <foreach collection = "projectIdList" item = "id" open = "(" separator = "," close = ")">
                    #{id}
                </foreach>
            </if>

这样生成的sql还是 project.id in ('1', '2', '3')

外部传入数组

mapper中

public int deleteUserRole(Long[] ids);

xml中

<delete id="deleteUserRole" parameterType="Long">
   delete from sys_user_role where user_id in
 	<foreach collection="array" item="userId" open="(" separator="," close=")">
 			#{userId}
        </foreach> 
</delete>

外部传入pojo列表

mapper中

public int batchUserRole(List<SysUserRole> userRoleList);

xml中

insert into sys_user_role(user_id, role_id) values
<foreach item="item" index="index" collection="list" separator=",">
	(#{item.userId},#{item.roleId})
</foreach>

pojo中有userId和roleId属性