使用Mybatis進行模糊查詢的幾種常用方法
阿新 • • 發佈:2019-01-08
在Mybaits中,可有3種模糊查詢的方式
一、使用${ }
如果SQL語句是 LIKE '%#{tag1}%' ,會被編譯為:'%?%' 。 這樣的話就被當成是一個字串了。
的確在專案裡面報這個錯,我就是從這個坑裡爬出來的。
應該把#修改為$ ,就像下面這樣。
<select id="getSimilarTag" resultType="com.ssi.domains.article.entity.Tag"> SELECT * FROM t_tag <if test="tag1 !=null and tag1 !=''"> <where> name LIKE '%${tag1}%' </where> </if> </select>
這樣的壞處就是不能夠防止SQL注入。因為${ }是拼接的SQL語句,因此不能夠防止SQL注入。
二、把模糊查詢的 %加上引號
就像這樣子, "%"#{param}"%"
<select id="getSimilarTag" resultType="com.ssi.domains.article.entity.Tag"> SELECT * FROM t_tag <if test="tag1 !=null and tag1 !=''"> <where> name LIKE "%"#{tag1}"%" </where> </if> </select>
三、使用函式進行拼
concat(a,b)函式能夠拼接字串。如下
<select id="getSimilarTag" resultType="com.ssi.domains.article.entity.Tag"> SELECT * FROM t_tag <if test="tag1 !=null and tag1 !=''"> <where> name LIKE concat(concat("%",#{tag1}),"%") </where> </if> </select>