最近新项目使用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>