背景:需要通过mybatis实现简单的字段like模糊查询,%如何处理
方法一:
完整范例查询语句如下:
<select id="queryRecord" resultType="db.model.Record"
parameterType="java.lang.String">
select a.recordId as recordID,a.name as name,
TRIM(TRAILING '.' from b.name) as zoneName,a.content as content,d.name as envName
from records as a
left join zones as b on a.zoneID = b.zoneID
left join (select distinct(zoneId),env from profile) as c on b.zoneID = c.zoneId
left join t_enviroment as d on c.env = d.id
where a.content like concat('%',#{searchText},'%') or
concat(a.name,'.',TRIM(TRAILING '.' from b.name)) like concat('%',#{searchText},'%')
order by a.recordId;
</select>
通过concat函数,将%和搜索关键字链接起来:
like concat('%',#{searchText},'%')
方法二:
参数直接添加%,比如还是上面的查询:
// java代码
searchText = '%' +searchText + '%';
queryRecord(searchText);
查询语句:
<select id="queryRecord" resultType="db.model.Record"
parameterType="java.lang.String">
select a.recordId as recordID,a.name as name,
TRIM(TRAILING '.' from b.name) as zoneName,a.content as content,d.name as envName
from records as a
left join zones as b on a.zoneID = b.zoneID
left join (select distinct(zoneId),env from profile) as c on b.zoneID = c.zoneId
left join t_enviroment as d on c.env = d.id
where a.content like #{searchText}
or concat(a.name,'.',TRIM(TRAILING '.' from b.name)) like #{searchText}
order by a.recordId;
</select>