注:本文中的一切內容是基於Spring-boot項目進行的研究,使用其他的方式可能會有一些不同。
建議在閱讀本博客前,先閱讀前一篇:【原創】Mybaitis生命週期源碼解析-XML配置啓動--轉載請註明出處
一、Spring-Mybatis準備測試代碼
由於基本代碼過多,此處不再細述。僅貼出用於進行測試的部分代碼:
package com.zhou.controller;
import com.zhou.mapper.BlogMapper;
import com.zhou.pojo.Blog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
@Controller
@RequestMapping("/")
public class AppController {
@Autowired
private BlogMapper blogMapper;
@RequestMapping("hello/{key}")
@ResponseBody
@Transactional
public String hello(@PathVariable("key") String key){
Blog blog = blogMapper.selectBlog(10, new ArrayList<>());
blogMapper.updateBlog(12345, key);
throw new RuntimeException("123123123");
}
}
在一個已經添加mybatis的項目中,添加上方代碼即可進行測試。其中的update方法,和select方法可以隨意填寫。
二、服務啓動Mybatis初始化
三、Sql執行
四、總結
在進行初始化時,mybatis利用MapperScannerConfigurer類,來將自己的mapper註冊到了Spring中,在Spring將所有的bean描述信息收集完成後,進行初始化bean的信息,此時調用了SqlSessionTemplate類來進行Mapper對象的初始化,使每一個MapperProxy對象中,都持有的是SqlSessionTemplate對象的引用。而SqlSessionTemplate對象本身並不直接進行執行sql。就使每一次在MapperProxy執行Sql的時候,可以做到單獨使用新的JdbcConnection進行處理。