在项目(基于SSM+mysql)中需要使用到like 条件,于是搜索了下相关的博客,发现网上各种错误真是害死人,什么concat写成cancat,什么标点符号错误,以及就一句话的博客。。故在此写此博客方便以后阅读。
like网上有3种方案,在此还是都贴出来吧,博主使用的第三种方案。。省时高效。。
方法1:参数中直接加入%%
param.setUsername("%amos%");
param.setPassword("%amos%");
<select id="selectPersons" resultType="person" parameterType="person">
select id,username,password from person <where>
<if test="username!=null"> AND username LIKE #{username}</if>
<if test="password!=null">AND password LIKE #{password}</if> </where>
</select>
方法2:通过mybatis的bind标签实现:
<select id="selectPersons" resultType="person" parameterType="person">
<bind name="pattern" value="'%' + _parameter.username + '%'" />
select id,sex,age,username,password
from person
where username LIKE #{pattern}
</select>
此种方法网上各路大神表示都遇到过错误,博主因为时间问题还没测试
方法3:使用mysql函数 CONCAT
where username LIKE concat('%',#{username},'%')