1. 程式人生 > >Mybatis 中在xxx.mapper書寫模糊查詢

Mybatis 中在xxx.mapper書寫模糊查詢

1.在mybatis中,書寫sql,有時候會有一些不細心,如:

  <!-- 首頁商品 關鍵字搜尋-->
  <select id="getGoodsByLikeTitle" resultMap="BaseResultMap">
    SELECT
    <!-- 詳情 -->
    gd.pay_price,
    gd.id,
    gd.couponamount,
    gd.sale_point,
    gd.earn_point,
    gd.stock_quantity,
    gd.site_id,
    gd.vip_level,
    <!-- 商品 -->
    g.id AS 'goodId',
    g.title AS 'goodTitle',
    g.img_url AS 'goodImgUrl',
    g.sale_price AS 'goodSalePrice',
    g.sale_count AS 'goodSaleCount',
    g.link_url AS 'goodLinkUrl',
    g.tags AS 'goodTags',
    g.summary AS 'goodSummary',
    g.series_no AS 'goodSeriesNo',
    g.spec_desc AS 'goodSpecDesc',
    g.weight AS 'goodWeight',
    g.add_time AS 'goodAddTime'
    FROM goods_detail AS gd
    INNER JOIN goods AS g
    ON gd.goods_id=g.id
    WHERE g.satus=1
    AND gd.site_id=#{siteId}
    AND g.title like CONCAT('%',#{wkeyword},'%')
    ORDER BY g.add_time DESC
  </select>
如果上述中的sql like 後面用的是'%${wkeyword}%',看似沒有錯,但你在呼叫時輸入“ ` ”引號間的符號,sql 就無法識別,即會報錯。如果用CONCAT('%',#{wkeyword},'%') 來替代 '%${wkeyword}%',則萬事大吉。具體這個是怎樣一個原理不是太清楚,看了很多文件都說是#{}與${}的不同,自己積累一下,避免後期遇到。