MyBatis底層實現模糊查詢的方法有哪些
阿新 • • 發佈:2021-06-23
MyBatis實現模糊查詢
模糊查詢在我們開發中是一項必不可缺少的重要內容。、
對於我們mybatis實現模糊查詢有五種方式,以下具體的實現步聚:
1. 新增模糊查詢的介面方法likeSearchUsers
/**
* 根據name模糊查詢
* @param name
* @return
*/
public List<User> likeSearcherUsers(String name);
2.配置介面方法對應的sql檔案
1) 配置佔位符方式#{}
<select id="likeSearcherUsers" parameterType="String" resultType="cn.offcn.entity.User"> select * from user where name like #{name} </select> <!--此時如果要實現模糊查詢,查詢的關鍵字前後需要帶有%,如查詢姓名中帶有王的,這樣寫查詢關鍵字:%王% -->
2) 配置拼接字串方式${}——存在sql注入問題
<select id="likeSearcherUsers" parameterType="String" resultType="cn.offcn.entity.User">
select * from user where name like '%${value}%'
</select>
我們在上面將原來的#{}佔位符,改成了${value}。
注意如果用模糊查詢的這種寫法,那麼${value}的寫法就是固定的,不能寫成其它名字。
3) 配置mysql函式方式concat
<select id="likeSearcherUsers" parameterType="String" resultType="cn.offcn.entity.User"> select * from user where name like concat('%',#{name},'%') </select> <!--函式方式concat只能用在mysql資料庫中,如果用在其他資料庫會有問題-->
4)動態標籤
<select id="getPersonByLikeName2" resultMap="BaseResultMap">
<bind name="personName" value="'%' + _parameter.getName() + '%'"></bind>
select * from person where p_name like #{personName}
</select>
<!--此種方法模糊查詢的只能是實體類物件,不能是基本資料型別資料-->
5)最佳方式——配置佔位符方式#{}實現模糊查詢且避免sql注入
<select id="getPersonByLikeName" resultMap="BaseResultMap">
select * from person where p_name like '%' #{name} '%'
</select>
<!--此種方法#{name}左右空格不可忽略-->
3.#{}和${}的區別
1.#{}是預編譯處理,${}是字串替換(有可能會產生sql注入問題)。
2.Mybatis在處理${}時,就是把${}替換成變數的值。
3.Mybatis在處理#{}時,會將 sql 中的#{}替換為?號,呼叫 PreparedStatement 的 set 方法來賦值。
4.使用#{}可以有效的防止 SQL 注入,提高系統安全性。