mybatis实现模糊查询的几种方式

最近新项目使用mybatis作为ORM,由于之前都是使用hibernate,

对mybatis使用经验不多。到mybatis官网学习。

后面会多做这方面的总结,作为日后工作的参考。

今天要实现的时模糊查询。项目使用的时mysql,其他数据库可能需要修改。

1,使用concat方法

<select id="getUserList" resultType="User">
select * from user 
 <where>
       <if test="name != null and name!= '' ">
           and user_name like concat('%',#{userName},'%')
       </if>
       <if test="email != null and email != '' ">
            and user_email = #{userEmail}
       </if>
 </where>
</select>

2,使用bind标签

<select id="getUserList" resultType="User">
<bind name="namelike" value="'%'+userName+'%'"/>
select * from user 
 <where>
       <if test="name != null and name!= '' ">
           and user_name like #{namelike}
       </if>
       <if test="email != null and email != '' ">
            and user_email = #{userEmail}
       </if>
 </where>
</select>

----------------------2018年11月16日--更新---------------

最近在整理代码的过程中发现了一个新的方式,虽然和2有些类似,但是实现方式不同,可以参考一下

3,在java代码中对传递的参数进行拼接,使其满足要求

String username = "%" + user.getUsername() + "%";
user.setUserName(username);

这样讲user传递到xml中,可以直接使用,不用加bind标签

<select id="getUserList" resultType="User">
select * from user 
 <where>
       <if test="name != null and name!= '' ">
           and user_name like #{namelike}
       </if>
       <if test="email != null and email != '' ">
            and user_email = #{userEmail}
       </if>
 </where>
</select>

参考:http://www.mybatis.org/mybatis-3/zh/dynamic-sql.html

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值