美文网首页
mybatis实现模糊查询时%%的处理

mybatis实现模糊查询时%%的处理

作者: 测试你个头 | 来源:发表于2017-02-14 16:24 被阅读0次

    背景:需要通过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>
    

    相关文章

      网友评论

          本文标题:mybatis实现模糊查询时%%的处理

          本文链接:https://www.haomeiwen.com/subject/opmvittx.html