mybatis多条件模糊查询

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

需求:
在这里插入图片描述
查询满足搜索条件其中任意一个条件的用户,为空则不添加此条件

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条件如果参数为空则不拼接sql-->
		<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 '%张%'
  • 9
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值