淺談mybatis mapper.xml檔案中$和#的區別
阿新 • • 發佈:2020-11-29
#{}表示一個佔位符即?,可以有效防止sql注入。在使用時不需要關心引數值的型別,mybatis會自動進行java型別和jdbc型別的轉換。
#{}可以接收簡單型別值或pojo屬性值,如果傳入簡單型別值,#{}括號中可以是任意名稱。
<!-- 根據名稱模糊查詢使用者資訊 --> <select id="findUserById" parameterType="String" resultType="user"> select * from user where username like CONCAT(CONCAT('%',#{name}),'%') </select>
${}可以將parameterType 傳入的內容拼接在sql中且不進行jdbc型別轉換。
${}可以接收簡單型別值或pojo屬性值,如果傳入簡單型別值,${}括號中名稱只能是value。
<!-- 根據名稱模糊查詢使用者資訊 --> <select id="selectUserByName" parameterType="string" resultType="user"> select * from user where username like '%${value}%' </select>
對於order by排序,使用#{}將無法實現功能,應該寫成如下形式:
ORDER BY ${columnName}
另外,對於mybatis逆向工程生成的程式碼中,進行模糊查詢呼叫andXxxLike()方法時,需要手動加%,如下:
CustomerExample customerExample=new CustomerExample();
customerExample.or().andNameLike("%"+name+"%");
補充知識:Mybatis條件if test使用列舉值
1 正確
package com.weather.weatherexpert.common.utils; /** * <p>Title: </p> * <p>Description: </p> * * @Author * @CreateTime */ public enum City { XINZHOU(100002,"忻州"),DATONG(100003,"大同"),TAIYUAN(100001,"太原"); private final Integer code; private final String name; City(Integer value,String desc) { this.code = value; this.name = desc; } public Integer getCode() { return code; } public String getName() { return name; } }
xml:
<!--<if test="cityName == @com.weather.weatherexpert.common.utils.City.XINZHOU@getName"><!–wrong,java.lang.ClassNotFoundException: Unable to resolve class: com.weather.weatherexpert.common.utils.City.XINZHOU–>--> <!--<if test="cityName == @com.weather.weatherexpert.common.utils.City@XINZHOU@getName"><!–wrong,[org.apache.ibatis.ognl.ParseException: Encountered " "@" "@ "" at line 1,column 65.–>--> <if test="cityName == @[email protected]"><!--right--> area_table </if> where 1=1 <if test="cityName == @[email protected]"><!--right--> and city_name=#{cityName} </if>
2 錯誤
package com.weather.weatherexpert.common.utils; /** * <p>Title: </p> * <p>Description: </p> * * @Author * @CreateTime */ public class CityClass { public static enum CityEnum { XINZHOU(100002,"太原"); private final Integer code; private final String name; CityEnum(Integer value,String desc) { this.code = value; this.name = desc; } public Integer getCode() { return code; } public String getName() { return name; } } }
xml:
/* Caused by: org.apache.ibatis.builder.BuilderException: Error evaluating expression 'cityName == @com.weather.weatherexpert.common.utils.CityClass@CityEnum.XINZHOU.getName'. Cause: org.apache.ibatis.ognl.OgnlException: Could not get static field CityEnum from class com.weather.weatherexpert.common.utils.CityClass [java.lang.NoSuchFieldException: CityEnum]*/ <if test="cityName == @com.weather.weatherexpert.common.utils.CityClass@CityEnum.XINZHOU.getName"><!--wrong--> area_table </if>
可見,直接定義的列舉類可以正常使用,在類中定義的列舉類這樣使用會報錯,可能方法還沒有找到。
以上這篇淺談mybatis mapper.xml檔案中$和#的區別就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。