复杂查询 --- 动态SQL

本文介绍了在Mybatis中处理复杂查询的两种方法:使用`if`和`where`标签避免多条件查询时的SQL错误,以及通过`foreach`标签遍历集合实现动态IN查询。此外,还探讨了如何通过定义SQL片段来减少代码冗余,提高Mybatis映射文件的可维护性。
摘要由CSDN通过智能技术生成

复杂查询 — 动态SQL

多条件查询

普通的sql查询多条判断条件时

select * from emp 
where 1=1 and ename = ? and job = ? and sal = ?

当其中一个条件为空时或者未提供会报错

mybatis提供了 if 标签

<if test="name != null">
    and ename like concat("%",#{name},"%")
</if>

判断失败则不加入sql语句

实例

//map传参
List<Emp> selectByCondition1(Map<String,Object> searchMap);
//顺序传参
List<Emp> selectByCondition2(String ename,String job,Double sal);
//对象传参
List<Emp> selectByCondition3(SearchMap searchMap);
public class SearchMap {
   
    private String name;
    private String job;
    private Double sal;
}
<select id="selectByCondition3" parameterType="hasmap" resultMap="empMap">
	select * from emp where
	<if test="ename != null">
		ename like concat("%",#{ename},"%")
	</if>
	<if test="job != null">
		and job  = #{job}
	</if>
	<if test="sal != null">
		and sal > #{sal}
	</if>
</select>

<select 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值