本文將會簡單介紹一下MyBatis的CRUD以及結合源碼講解一下MyBatis對參數的處理。
作為一個ORM框架,最基本的使用也就是CRUD了,MyBatis提供了兩種方法:xml配置文件和動態注解。個人推薦xml配置文件,方式畢竟注解方式還是要將sql寫在代碼中,并且動態查詢的時候還用嵌套script標簽,相當麻煩,扯遠了,回歸主題。
## 1.CRUD
? ? ? 創建一個dao接口,定義方法:
```
package com.mybatis.learn.dao;
import com.mybatis.learn.bean.Employee;
public interface EmployeeMapper {
? ? public Employee getEmpById(Integer id);
? ? public int addEmployee(Employee employee);
? ? public boolean updateEmployeeById(Employee employee);
? ? public void deleteEmployeeById(Integer id);
}
```
? ? 創建一個xml文件并在其中編寫sql語句,注意將Mapper與xml文件進行綁定(在mybatis-config.xml文件中使用Mapper標簽)。
```
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
? ? ? ? PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
? ? ? ? "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.learn.dao.EmployeeMapper">
? ? <!--
? ? ? ? resultType:指定查詢結果的返回值類型;MyBatis會自動創建一個ResultMap對象,
? ? ? ? ? ? 然后基于查找出來的屬性名進行鍵值對封裝,看到返回類型是Blog對象,
? ? ? ? ? ? 從ResultMap中取出與Blog對象對應的鍵值對進行賦值。
? ? ? ? resultMap:原理同上,當提供的返回類型是resultMap時,因為Map不能很好表示領域模型,
? ? ? ? ? ? 就需要自己再進一步的把它轉化為對應的對象,這常常在復雜查詢中很有作用。
? ? -->
? ? <select id="getEmpById" resultType="com.mybatis.learn.bean.Employee">
? ? select id, last_name lastName, gender, email from tbl_employee where id = #{id}
? </select>
<!--
? ? useGeneratedKeys: true為使用主鍵綁定,
? ? keyProerty: 指定主鍵,
? ? parameterKey: 指定參數類型
-->
? ? <insert id="addEmployee" parameterType="com.mybatis.learn.bean.Employee"
? ? ? ? ? ? statementType="PREPARED" useGeneratedKeys="true" keyProperty="id">
? ? ? ? insert into tbl_employee (last_name, gender, email) values (#{lastName}, #{gender}, #{email})
? ? </insert>
? ? <update id="updateEmployeeById" parameterType="com.mybatis.learn.bean.Employee">
? ? ? ? update tbl_employee set last_name=#{lastName}, gender=#{gender}, email=#{email} where id=#{id}
? ? </update>
? ? <delete id="deleteEmployeeById" parameterType="java.lang.Integer">
? ? ? ? delete from tbl_employee where id=#{id}
? ? </delete>
</mapper>
```
? ? 其中, 各自方法的標簽見文知意。需要注意的是,namespace寫你的Mapper類的全類名,然后各自的方法中的id填寫你的方法名,從而完成了綁定。
## 2.參數處理
? ? 要是只能一句話概括的話,MyBatis會將參數封裝為一個map,這是結論,下面詳細說明:
? ? 大致分為兩種情況:
### 1.單個參數且沒有@param注解時:
? ? ? MyBatis不會進行特殊處理(看上去,其實這種情況只是處理的一種解決方案,后面結合源碼會詳細介紹),即:#{參數名/任意名}:取出參數值。注意,#{}中不一定要是準確的參數名,比如錯把id寫成了iddd一樣可以運行,因為MyBatis只是取出對應位置的值而已。
### 2.多個參數或者單個參數有@param注解時:
? ? ? MyBatis會將參數封裝成一個map:
? ? ? ? ? key:param1...paramN,或者參數的索引也可以
? value:傳入的參數值
? ? ? ? ? #{}就是從map中獲取指定的key的值;
在MyBatis處理參數過程中,可能會拋出的異常:(當你寫成#{id}并且沒有加上@param(“id”)時)
? ? ? org.apache.ibatis.binding.BindingException:
Parameter 'id' not found.
Available parameters are [1, 0, param1, param2]
報這個異常的例子:
```
public Employee getEmpByIdAndLastName(Integer id,String lastName);
取值:#{id},#{lastName}
```
? ? 當然,當你的參數過多時,建議你傳入的參數為一個POJO,這樣就無需使用@param,也能正常傳參。
? ? ? ? ? ? #{屬性名}:取出傳入的pojo的屬性值 。
? ? 而當沒有對應的POJO時,也可以直接傳入一個map,反正MyBatis也會封裝一個map,你只需在存入
? ? ? ? ? ? map時指定號key和value就行了。
? ? 如果多個參數不是業務模型中的數據,但是經常要使用,推薦來編寫一個TO(Transfer Object)數據
? ? ? ? ? 傳輸對象
? ? ? ? ? Page{
? ? ? ? int index;
? ? ? ? int size;
? ? ? ? ? }
OK,相信你大致明白了,來搞一下練習吧:
```
public Employee getEmp(@Param("id")Integer id,String lastName);
//取值:id==>#{id/param1}? lastName==>#{param2}
public Employee getEmp(Integer id,@Param("e")Employee emp);
//取值:id==>#{param1}? ? lastName===>#{param2.lastName/e.lastName}
/**
特別注意:如果是Collection(List、Set)類型或者是數組,也會特殊處理。也是把傳入的list或者數組封裝在map中。key:Collection(collection),如果是List還可以使用這個key(list),數組(array)
**/
public Employee getEmpById(List<Integer> ids);
取值:取出第一個id的值:? #{list[0]}
```
Ok,現在貼一下部分源碼,我加了一點注解:
```
(@Param("id")Integer id,@Param("lastName")String lastName);
ParamNameResolver解析參數封裝map的;
//1、names:{0=id, 1=lastName};構造器的時候就確定好了
確定流程:
1.獲取每個標了param注解的參數的@Param的值:id,lastName;? 賦值給name;
2.每次解析一個參數給map中保存信息:(key:參數索引,value:name的值)
name的值:
標注了param注解:注解的值
沒有標注:
1.全局配置:useActualParamName(jdk1.8):name=參數名
2.name=map.size();相當于當前元素的索引
{0=id, 1=lastName,2=2}
//args【1,"Tom",'hello'】:
public Object getNamedParams(Object[] args) {
? ? final int paramCount = names.size();
? ? //1、參數為null直接返回
? ? if (args == null || paramCount == 0) {
? ? ? return null;?
? //2、如果只有一個元素,并且沒有Param注解;args[0]:單個參數直接返回
? ? } else if (!hasParamAnnotation && paramCount == 1) {
? ? ? return args[names.firstKey()];
? ? //3、多個元素或者有Param標注
? ? } else {
? ? ? final Map<String, Object> param = new ParamMap<Object>();
? ? ? int i = 0;?
? ? ? //4、遍歷names集合;{0=id, 1=lastName,2=2}
? ? ? for (Map.Entry<Integer, String> entry : names.entrySet()) {
? ? ? ? ? //names集合的value作為key;? names集合的key又作為取值的參考args[0]:args【1,"Tom"】:
? ? ? //eg:{id=args[0]:1,lastName=args[1]:Tom,2=args[2]}
? ? ? ? param.put(entry.getValue(), args[entry.getKey()]);? ?
? ? ? ? // add generic param names (param1, param2, ...)param
? ? ? ? //額外的將每一個參數也保存到map中,使用新的key:param1...paramN
? ? ? ? //效果:有Param注解可以#{指定的key},或者#{param1}
? ? ? ? final String genericParamName = GENERIC_NAME_PREFIX + String.valueOf(i + 1);
? ? ? ? // ensure not to overwrite parameter named with @Param
? ? ? ? if (!names.containsValue(genericParamName)) {
? ? ? ? ? param.put(genericParamName, args[entry.getKey()]);
? ? ? ? }
? ? ? ? i++;
? ? ? }
? ? ? return param;
? ? }
? }
}
```
一點補充:
$ 和#的不同:
```
//? #{}是一般情況都使用的,在MyBatis預編譯sql的時候會將對應的#{參數名}替換為?,還能防止sql注入。
//? ${}的存在也是有價值的,雖然會引起sql注入,但是能解決一些#{}無法搞定的場景,比如排序,表名字等等,舉例如下:
@Select("select * from user where ${column} = #{value}")
User findByColumn(@Param("column") String column, @Param("value") String value);
//其中 ${column} 會被直接替換,而 #{value} 會被使用 ? 預處理.
```
###? #{}:更豐富的用法:
規定參數的一些規則:
javaType、 jdbcType、 mode(存儲過程)、 numericScale、
resultMap、 typeHandler、 jdbcTypeName、 expression(未來準備支持的功能);
jdbcType通常需要在某種特定的條件下被設置:
在我們數據為null的時候,有些數據庫可能不能識別mybatis對null的默認處理。比如Oracle(報錯);
JdbcType OTHER:無效的類型;因為mybatis對所有的null都映射的是原生Jdbc的OTHER類型,oracle不能正確處理;
由于全局配置中:jdbcTypeForNull=OTHER;oracle不支持;兩種辦法
1、#{email,jdbcType=OTHER};
2、jdbcTypeForNull=NULL
<setting name="jdbcTypeForNull" value="NULL"/>