欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

MyBatis執(zhí)行Sql的流程實(shí)例解析

 更新時(shí)間:2019年12月23日 16:30:56   作者:寫(xiě)代碼的木公  
這篇文章主要介紹了MyBatis執(zhí)行Sql的流程實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

這篇文章主要介紹了MyBatis執(zhí)行Sql的流程實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

本博客著重介紹MyBatis執(zhí)行Sql的流程,關(guān)于在執(zhí)行過(guò)程中緩存、動(dòng)態(tài)SQl生成等細(xì)節(jié)不在本博客中體現(xiàn),相應(yīng)內(nèi)容后面再單獨(dú)寫(xiě)博客分析吧。

還是以之前的查詢(xún)作為列子:

public class UserDaoTest {

  private SqlSessionFactory sqlSessionFactory;

  @Before
  public void setUp() throws Exception{
    ClassPathResource resource = new ClassPathResource("mybatis-config.xml");
    InputStream inputStream = resource.getInputStream();
    sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  }

  @Test
  public void selectUserTest(){
    String id = "{0003CCCA-AEA9-4A1E-A3CC-06D884BA3906}";
    SqlSession sqlSession = sqlSessionFactory.openSession();
    CbondissuerMapper cbondissuerMapper = sqlSession.getMapper(CbondissuerMapper.class);
    Cbondissuer cbondissuer = cbondissuerMapper.selectByPrimaryKey(id);
    System.out.println(cbondissuer);
    sqlSession.close();
  }

}

之前提到拿到sqlSession之后就能進(jìn)行各種CRUD操作了,所以我們就從sqlSession.getMapper這個(gè)方法開(kāi)始分析,看下整個(gè)Sql的執(zhí)行流程是怎么樣的。

獲取Mapper

進(jìn)入sqlSession.getMapper方法,會(huì)發(fā)現(xiàn)調(diào)的是Configration對(duì)象的getMapper方法:

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
  //mapperRegistry實(shí)質(zhì)上是一個(gè)Map,里面注冊(cè)了啟動(dòng)過(guò)程中解析的各種Mapper.xml
  //mapperRegistry的key是接口的全限定名,比如com.csx.demo.spring.boot.dao.SysUserMapper
  //mapperRegistry的Value是MapperProxyFactory,用于生成對(duì)應(yīng)的MapperProxy(動(dòng)態(tài)代理類(lèi))
  return mapperRegistry.getMapper(type, sqlSession);
}

進(jìn)入getMapper方法:

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
  final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
  //如果配置文件中沒(méi)有配置相關(guān)Mapper,直接拋異常
  if (mapperProxyFactory == null) {
   throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
  }
  try {
   //關(guān)鍵方法
   return mapperProxyFactory.newInstance(sqlSession);
  } catch (Exception e) {
   throw new BindingException("Error getting mapper instance. Cause: " + e, e);
  }
 }

進(jìn)入MapperProxyFactory的newInstance方法:

public class MapperProxyFactory<T> {

 private final Class<T> mapperInterface;
 private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();

 public MapperProxyFactory(Class<T> mapperInterface) {
  this.mapperInterface = mapperInterface;
 }

 public Class<T> getMapperInterface() {
  return mapperInterface;
 }

 public Map<Method, MapperMethod> getMethodCache() {
  return methodCache;
 }

 //生成Mapper接口的動(dòng)態(tài)代理類(lèi)MapperProxy
 @SuppressWarnings("unchecked")
 protected T newInstance(MapperProxy<T> mapperProxy) {
  return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
 }
 
 public T newInstance(SqlSession sqlSession) {
  final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
  return newInstance(mapperProxy);
 }

}

下面是動(dòng)態(tài)代理類(lèi)MapperProxy,調(diào)用Mapper接口的所有方法都會(huì)先調(diào)用到這個(gè)代理類(lèi)的invoke方法(注意由于Mybatis中的Mapper接口沒(méi)有實(shí)現(xiàn)類(lèi),所以MapperProxy這個(gè)代理對(duì)象中沒(méi)有委托類(lèi),也就是說(shuō)MapperProxy干了代理類(lèi)和委托類(lèi)的事情)。好了下面重點(diǎn)看下invoke方法。

//MapperProxy代理類(lèi)
public class MapperProxy<T> implements InvocationHandler, Serializable {

 private static final long serialVersionUID = -6424540398559729838L;
 private final SqlSession sqlSession;
 private final Class<T> mapperInterface;
 private final Map<Method, MapperMethod> methodCache;

 public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
  this.sqlSession = sqlSession;
  this.mapperInterface = mapperInterface;
  this.methodCache = methodCache;
 }

 @Override
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  try {
   if (Object.class.equals(method.getDeclaringClass())) {
    return method.invoke(this, args);
   } else if (isDefaultMethod(method)) {
    return invokeDefaultMethod(proxy, method, args);
   }
  } catch (Throwable t) {
   throw ExceptionUtil.unwrapThrowable(t);
  }
  //獲取MapperMethod,并調(diào)用MapperMethod
  final MapperMethod mapperMethod = cachedMapperMethod(method);
  return mapperMethod.execute(sqlSession, args);
 }

 private MapperMethod cachedMapperMethod(Method method) {
  MapperMethod mapperMethod = methodCache.get(method);
  if (mapperMethod == null) {
   mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
   methodCache.put(method, mapperMethod);
  }
  return mapperMethod;
 }

 @UsesJava7
 private Object invokeDefaultMethod(Object proxy, Method method, Object[] args)
   throws Throwable {
  final Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class
    .getDeclaredConstructor(Class.class, int.class);
  if (!constructor.isAccessible()) {
   constructor.setAccessible(true);
  }
  final Class<?> declaringClass = method.getDeclaringClass();
  return constructor
    .newInstance(declaringClass,
      MethodHandles.Lookup.PRIVATE | MethodHandles.Lookup.PROTECTED
        | MethodHandles.Lookup.PACKAGE | MethodHandles.Lookup.PUBLIC)
    .unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args);
 }

 /**
  * Backport of java.lang.reflect.Method#isDefault()
  */
 private boolean isDefaultMethod(Method method) {
  return ((method.getModifiers()
    & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) == Modifier.PUBLIC)
    && method.getDeclaringClass().isInterface();
 }
}

所以這邊需要進(jìn)入MapperMethod的execute方法:

public Object execute(SqlSession sqlSession, Object[] args) {
  Object result;
  //判斷是CRUD那種方法
  switch (command.getType()) {
   case INSERT: {
    Object param = method.convertArgsToSqlCommandParam(args);
    result = rowCountResult(sqlSession.insert(command.getName(), param));
    break;
   }
   case UPDATE: {
    Object param = method.convertArgsToSqlCommandParam(args);
    result = rowCountResult(sqlSession.update(command.getName(), param));
    break;
   }
   case DELETE: {
    Object param = method.convertArgsToSqlCommandParam(args);
    result = rowCountResult(sqlSession.delete(command.getName(), param));
    break;
   }
   case SELECT:
    if (method.returnsVoid() && method.hasResultHandler()) {
     executeWithResultHandler(sqlSession, args);
     result = null;
    } else if (method.returnsMany()) {
     result = executeForMany(sqlSession, args);
    } else if (method.returnsMap()) {
     result = executeForMap(sqlSession, args);
    } else if (method.returnsCursor()) {
     result = executeForCursor(sqlSession, args);
    } else {
     Object param = method.convertArgsToSqlCommandParam(args);
     result = sqlSession.selectOne(command.getName(), param);
    }
    break;
   case FLUSH:
    result = sqlSession.flushStatements();
    break;
   default:
    throw new BindingException("Unknown execution method for: " + command.getName());
  }
  if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
   throw new BindingException("Mapper method '" + command.getName() 
     + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
  }
  return result;
 }

然后,通過(guò)一層一層的調(diào)用,最終會(huì)來(lái)到doQuery方法, 這兒咱們就隨便找個(gè)Excutor看看doQuery方法的實(shí)現(xiàn)吧,我這兒選擇了SimpleExecutor:

public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
  Statement stmt = null;
  try {
   Configuration configuration = ms.getConfiguration();
   //內(nèi)部封裝了ParameterHandler和ResultSetHandler
   StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
   stmt = prepareStatement(handler, ms.getStatementLog());
   //StatementHandler封裝了Statement, 讓 StatementHandler 去處理
   return handler.<E>query(stmt, resultHandler);
  } finally {
   closeStatement(stmt);
  }
 }

接下來(lái),咱們看看StatementHandler 的一個(gè)實(shí)現(xiàn)類(lèi) PreparedStatementHandler(這也是我們最常用的,封裝的是PreparedStatement), 看看它使怎么去處理的:

public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
   //到此,原形畢露, PreparedStatement, 這個(gè)大家都已經(jīng)滾瓜爛熟了吧
  PreparedStatement ps = (PreparedStatement) statement;
  ps.execute();
  //結(jié)果交給了ResultSetHandler 去處理,處理完之后返回給客戶(hù)端
  return resultSetHandler.<E> handleResultSets(ps);
 }

到此,整個(gè)調(diào)用流程結(jié)束。

簡(jiǎn)單總結(jié)

這邊結(jié)合獲取SqlSession的流程,做下簡(jiǎn)單的總結(jié):

  • SqlSessionFactoryBuilder解析配置文件,包括屬性配置、別名配置、攔截器配置、環(huán)境(數(shù)據(jù)源和事務(wù)管理器)、Mapper配置等;解析完這些配置后會(huì)生成一個(gè)Configration對(duì)象,這個(gè)對(duì)象中包含了MyBatis需要的所有配置,然后會(huì)用這個(gè)Configration對(duì)象創(chuàng)建一個(gè)SqlSessionFactory對(duì)象,這個(gè)對(duì)象中包含了Configration對(duì)象;
  • 拿到SqlSessionFactory對(duì)象后,會(huì)調(diào)用SqlSessionFactory的openSesison方法,這個(gè)方法會(huì)創(chuàng)建一個(gè)Sql執(zhí)行器(Executor組件中包含了Transaction對(duì)象),這個(gè)Sql執(zhí)行器會(huì)代理你配置的攔截器方法。
  • 獲得上面的Sql執(zhí)行器后,會(huì)創(chuàng)建一個(gè)SqlSession(默認(rèn)使用DefaultSqlSession),這個(gè)SqlSession中也包含了Configration對(duì)象和上面創(chuàng)建的Executor對(duì)象,所以通過(guò)SqlSession也能拿到全局配置;
  • 獲得SqlSession對(duì)象后就能執(zhí)行各種CRUD方法了。

以上是獲得SqlSession的流程,下面總結(jié)下本博客中介紹的Sql的執(zhí)行流程:

  • 調(diào)用SqlSession的getMapper方法,獲得Mapper接口的動(dòng)態(tài)代理對(duì)象MapperProxy,調(diào)用Mapper接口的所有方法都會(huì)調(diào)用到MapperProxy的invoke方法(動(dòng)態(tài)代理機(jī)制);
  • MapperProxy的invoke方法中唯一做的就是創(chuàng)建一個(gè)MapperMethod對(duì)象,然后調(diào)用這個(gè)對(duì)象的execute方法,sqlSession會(huì)作為execute方法的入?yún)ⅲ?/li>
  • 往下,層層調(diào)下來(lái)會(huì)進(jìn)入Executor組件(如果配置插件會(huì)對(duì)Executor進(jìn)行動(dòng)態(tài)代理)的query方法,這個(gè)方法中會(huì)創(chuàng)建一個(gè)StatementHandler對(duì)象,這個(gè)對(duì)象中同時(shí)會(huì)封裝ParameterHandler和ResultSetHandler對(duì)象。調(diào)用StatementHandler預(yù)編譯參數(shù)以及設(shè)置參數(shù)值,使用ParameterHandler來(lái)給sql設(shè)置參數(shù)。

Executor組件有兩個(gè)直接實(shí)現(xiàn)類(lèi),分別是BaseExecutor和CachingExecutor。CachingExecutor靜態(tài)代理了BaseExecutor。Executor組件封裝了Transction組件,Transction組件中又分裝了Datasource組件。

  • 調(diào)用StatementHandler的增刪改查方法獲得結(jié)果,ResultSetHandler對(duì)結(jié)果進(jìn)行封裝轉(zhuǎn)換,請(qǐng)求結(jié)束。

Executor、StatementHandler 、ParameterHandler、ResultSetHandler,Mybatis的插件會(huì)對(duì)上面的四個(gè)組件進(jìn)行動(dòng)態(tài)代理。

重要類(lèi)

  • MapperProxyFactory
  • MapperProxy
  • MapperMethod
  • SqlSession:作為MyBatis工作的主要頂層API,表示和數(shù)據(jù)庫(kù)交互的會(huì)話,完成必要數(shù)據(jù)庫(kù)增刪改查功能;
  • Executor:MyBatis執(zhí)行器,是MyBatis 調(diào)度的核心,負(fù)責(zé)SQL語(yǔ)句的生成和查詢(xún)緩存的維護(hù);
  • StatementHandler 封裝了JDBC Statement操作,負(fù)責(zé)對(duì)JDBC statement 的操作,如設(shè)置參數(shù)、將Statement結(jié)果集轉(zhuǎn)換成List集合。
  • ParameterHandler 負(fù)責(zé)對(duì)用戶(hù)傳遞的參數(shù)轉(zhuǎn)換成JDBC Statement 所需要的參數(shù),
  • ResultSetHandler 負(fù)責(zé)將JDBC返回的ResultSet結(jié)果集對(duì)象轉(zhuǎn)換成List類(lèi)型的集合;
  • TypeHandler 負(fù)責(zé)java數(shù)據(jù)類(lèi)型和jdbc數(shù)據(jù)類(lèi)型之間的映射和轉(zhuǎn)換
  • MappedStatement MappedStatement維護(hù)了一條<select|update|delete|insert>節(jié)點(diǎn)的封裝,
  • SqlSource 負(fù)責(zé)根據(jù)用戶(hù)傳遞的parameterObject,動(dòng)態(tài)地生成SQL語(yǔ)句,將信息封裝到BoundSql對(duì)象中,并返回
  • BoundSql 表示動(dòng)態(tài)生成的SQL語(yǔ)句以及相應(yīng)的參數(shù)信息

Configuration MyBatis所有的配置信息都維持在Configuration對(duì)象之中。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java類(lèi)的加載時(shí)機(jī)

    Java類(lèi)的加載時(shí)機(jī)

    這篇文章介紹了Java類(lèi)的加載時(shí)機(jī),文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-12-12
  • java WebSocket的實(shí)現(xiàn)以及Spring WebSocket示例代碼

    java WebSocket的實(shí)現(xiàn)以及Spring WebSocket示例代碼

    本篇文章主要介紹了java WebSocket的實(shí)現(xiàn)以及Spring WebSocket,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。
    2017-01-01
  • Springboot整合hibernate validator 全局異常處理步驟詳解

    Springboot整合hibernate validator 全局異常處理步驟詳解

    本文分步驟給大家介紹Springboot整合hibernate validator 全局異常處理,補(bǔ)呢文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2024-01-01
  • Spring MVC完全注解方式配置web項(xiàng)目

    Spring MVC完全注解方式配置web項(xiàng)目

    這篇文章主要為大家詳細(xì)介紹了Spring MVC完全注解方式配置web項(xiàng)目的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-10-10
  • Java解壓縮zip - 解壓縮多個(gè)文件或文件夾實(shí)例

    Java解壓縮zip - 解壓縮多個(gè)文件或文件夾實(shí)例

    本篇文章主要介紹了Java解壓縮zip - 解壓縮多個(gè)文件或文件夾實(shí)例,非常具有實(shí)用價(jià)值,有需要的可以了解一下。
    2016-12-12
  • java環(huán)境搭建教程

    java環(huán)境搭建教程

    這篇文章主要為大家詳細(xì)介紹了java環(huán)境的搭建教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-03-03
  • SpringBoot響應(yīng)Json數(shù)據(jù)亂碼通過(guò)配置的解決

    SpringBoot響應(yīng)Json數(shù)據(jù)亂碼通過(guò)配置的解決

    這篇文章主要介紹了SpringBoot響應(yīng)Json數(shù)據(jù)亂碼通過(guò)配置的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • SpringBoot任務(wù)調(diào)度器的實(shí)現(xiàn)代碼

    SpringBoot任務(wù)調(diào)度器的實(shí)現(xiàn)代碼

    SpringBoot自帶了任務(wù)調(diào)度器,通過(guò)注解的方式使用。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-12-12
  • JVM中的GC初識(shí)

    JVM中的GC初識(shí)

    GC(Garbage Collection)稱(chēng)之為垃圾回收,是對(duì)內(nèi)存中的垃圾對(duì)象,采用一定的算法進(jìn)行內(nèi)存回收的一個(gè)動(dòng)作,這篇文章主要介紹了JVM中的GC初識(shí),需要的朋友可以參考下
    2022-05-05
  • Java案例之HashMap集合存儲(chǔ)學(xué)生對(duì)象并遍歷

    Java案例之HashMap集合存儲(chǔ)學(xué)生對(duì)象并遍歷

    這篇文章主要介紹了Java案例之HashMap集合存儲(chǔ)學(xué)生對(duì)象并遍歷,創(chuàng)建一個(gè)HashMap集合,鍵是學(xué)號(hào)(String),值是學(xué)生對(duì)象(Student),存儲(chǔ)三個(gè)鍵值對(duì)元素并遍歷,下文具體操作需要的朋友可以參考一下
    2022-04-04

最新評(píng)論