Mybatis in条件传参的三种实现方式(直接$,List,[])
第一种方法
in 条件为拼接好的字符串
如果直接传入拼接好的where in 条件, 比如('111','222','333'),则需要使用${idlist}传参,即绝对引用,而不能使用#
如果使用#传参会被mybatis当成字符串再添加一层''引号,导致错误.
- 优点:简单方便,高效
- 缺点:不能防止SQL注入
第二种方法
in 条件为List对象
in条件直接传入List对象,让mybatis再去拼接生成in条件,这个很麻烦,但是可以防止SQL注入
第三种方法
in 条件为String[] 数组
in条件直接传入[]数组对象,让mybatis再去拼接生成in条件,这个很麻烦,但是可以防止SQL注入
如果项目大,其实可以同时重载三种都实现,我一般都会这样,实现三种DAO接口,service层相同方法名,根据不同的模块不同的需求调用不同的实现层
Service:
int deleteMenuByIdList(String idlist,int delcount,int lastsort);
int deleteMenuByIdList(List<String> idlist, int delcount,int lastsort);
int deleteMenuByIdList(String[] idlist, int delcount,int lastsort);Dao:
//用这种写法方便,idlist直接拼接好,xml中用 in ${idlist}接受参数
int deleteMenuByIdList(@Param("idlist")String idlist, @Param("delcount")int delcount, @Param("lastsort")int lastsort);
//用这种写法直接传List对象,xml中再写循环拼接,麻烦
int deleteMenuByIdList2(@Param("idlist")List<String> idlist, @Param("delcount")int delcount, @Param("lastsort")int lastsort);
//用这种写法直接传String[]数组,xml中再写循环拼接,麻烦
int deleteMenuByIdList3(@Param("idlist")String[] idlist, @Param("delcount")int delcount, @Param("lastsort")int lastsort);(2,3)的xml文件中不需要做修改,只需要修改一下id对应到DAO的方法名即可。
mappper.xml
1,
<delete id="deleteMenuByIdList" >
delete from s_menu where menu_id in ${idlist};
update s_menu set sort=sort-#{delcount} where sort >= #{lastsort} and menu_id not in ${idlist};
</delete>
2,
<delete id="deleteMenuByIdList2" >
delete from s_menu where menu_id in
<foreach collection="idlist" item="menu_id" separator="," open="(" close=")">
#{menu_id}
</foreach>
;update s_menu set sort=sort-#{delcount} where sort >= #{lastsort} and menu_id not in
<foreach collection="idlist" item="menu_id" separator="," open="(" close=")">
#{menu_id}
</foreach>;
</delete>
3,
<delete id="deleteMenuByIdList3" >
delete from s_menu where menu_id in
<foreach collection="idlist" item="menu_id" separator="," open="(" close=")">
#{menu_id}
</foreach>
;update s_menu set sort=sort-#{delcount} where sort >= #{lastsort} and menu_id not in
<foreach collection="idlist" item="menu_id" separator="," open="(" close=")">
#{menu_id}
</foreach>;
</delete>总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
SpringBoot与Quartz集成实现分布式定时任务集群的代码实例
今天小编就为大家分享一篇关于SpringBoot与Quartz集成实现分布式定时任务集群的代码实例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧2019-03-03
Springboot @Transactional使用时需注意的几个问题记录
本文详细介绍了Spring Boot中使用`@Transactional`注解进行事务管理的多个方面,包括事务的隔离级别(如REPEATABLE_READ)和传播行为(如REQUIRES_NEW),并指出了在同一个类中调用事务方法时可能遇到的问题以及解决方案,感兴趣的朋友跟随小编一起看看吧2025-01-01
SpringAop自定义切面注解、自定义过滤器及ThreadLocal详解
这篇文章主要介绍了SpringAop自定义切面注解、自定义过滤器及ThreadLocal详解,Aspect(切面)通常是一个类,里面可以定义切入点和通知(切面 = 切点+通知),execution()是最常用的切点函数,需要的朋友可以参考下2024-01-01
详解Java8的forEach(...)如何提供index值
这篇文章主要介绍了详解Java8的forEach(...)如何提供index值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2021-03-03
java组件commons-fileupload实现文件上传
这篇文章主要介绍了java借助commons-fileupload组件实现文件上传,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2016-10-10


最新评论