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


版权声明:本文为wobuaizhi原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。