MyBatis多条件查询

640?wx_fmt=png&wxfrom=5&wx_lazy=1

1.MyBatis多条件查询

1.1:使用实体类  将参数封装成对象

接口:

public List<User> getUserListByUser(User user);

Mapper映射文件:

<select id="getUserListByUser" resultType="User" parameterType="User">

select * from smbms_user where username like CONCAT('%',#{userName},'%') and userRole=#{userRole}

</select>

注意:#{}中参数名需要与对象的属性名一致

1.2:使用Map集合 将参数存入Map集合进行传递

接口:

public List<User> getUserListByUserMap(Map<String, String> map);

Mapper映射文件:

<select id="getUserListByUserMap" resultType="User" parameterType="map">

select * from smbms_user where username like CONCAT('%',#{userName},'%') and userRole=#{userRole}

</select>

注意:#{}中参数名需要与Map集合中的键名一致

1.3:使用@param注解传递多个参数

接口:

public List<User> getUserListByParam(@Param("userName")String username,@Param("userRole")Integer roleId);

Mapper映射文件:

<select id="getUserListByParam" resultType="User" >

select * from smbms_user where username like CONCAT('%',#{userName},'%') and userRole=#{userRole}

</select>

注意:使用@Param注解封装的参数 小括号中参数名需要与#{}中参数名一致

1.4:直接传入多个参数 使用下标获取

接口:

public List<User> getUserListByParam(String username,Integer roleId);

Mapper映射文件:

<select id="getUserListByParam" resultType="User" >

select * from smbms_user where username like CONCAT('%',#{0},'%') and userRole=#{1}

</select>

2.${}和#{}获取参数的区别?

2.1#{}会将参数转换成String类型进行处理(特殊字符会进行转义)  ${}不会

2.2使用#{}会进行sql预处理 也就是表示使用PreparedStatement进行执行sql语句 可以有效防止sql注入  但是使用${}不会

2.3一般在进行排序order by的时候使用${} eg:${value} (只有单个参数时使用${value}可以获取到参数值,多个参数依然使用对象属性或Map集合的键名)

2.4在能用#{}的时候就不要去用${}


posted @   天使不哭  阅读(156)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示