mybatis多条件模糊查询

mybatis+mysql实现多个模糊条件查询

需求:
mybatis多条件模糊查询_第1张图片
查询满足搜索条件其中任意一个条件的用户,为空则不添加此条件

SQL:

先查询日期区间2019-02~2019-03的信息(cust_createtime为日期字段名):

SELECT * FROM customer 
where DATE_FORMAT(cust_createtime,'%Y%m') 
BETWEEN '201902' and '201903'

所以此需求对应的sql:

SELECT * FROM customer 
where cust_name like '%阿里%' 
or cust_boss like '马' 
or DATE_FORMAT(cust_createtime,'%Y%m') BETWEEN '201902' and '201903'

Mapper接口(注意使用了@Param则不能再用索引传参)

 /**
     *  条件查询:公司名、董事长名、公司成立时间区域(开始时间、结束时间)
     * @param custName  公司名
     * @param custBoss  董事长
     * @param timeStart 成立时间范围
     * @param timeEnd   成立时间范围
     * @return  客户列表
     */
 List<Customer> findCustomer(@Param("custName") String custName, 
 	@Param("custBoss") String custBoss, 
 	@Param("timeStart") String timeStart, 
 	@Param("timeEnd") String timeEnd);

CustomerMapper.xml


<select id="findCustomer" resultMap="customer_list_map">
	select * from customer
	<where>
		
		<if test="custName != null and custName != '' ">
			cust_name like concat('%',#{custName},'%')
		if>
		<if test="custBoss != null and custBoss != '' ">
			or cust_boss like concat('%',#{custBoss},'%')
		if>
		<if test="timeStart != null and timeStart != '' and timeEnd != null and timeEnd != ''">
			or DATE_FORMAT(cust_createtime,'%Y%m') BETWEEN #{timeStart} and #{timeEnd}
		if>
	where>
select>

mysql中concat函数

功能:将多个字符串连接成一个字符串
使用方法:

 select * from customer where cust_name like concat('%','张','%')
 //最终为:
 select * from customer where cust_name like '%张%'

你可能感兴趣的:(mybatis)