日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

MyBatis创建SqlSession可以直接使用DefaultSqlSession 吗?

發布時間:2024/4/13 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 MyBatis创建SqlSession可以直接使用DefaultSqlSession 吗? 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

我們現在已經有一個DefaultSqlSessionFactory,按照編程式的開發過程,我們接下來就會創建一個SqlSession 的實現類,但是在Spring 里面,我們不是直接使用DefaultSqlSession 的,而是對它進行了一個封裝,這個SqlSession 的實現類就是SqlSessionTemplate。這個跟Spring 封裝其他的組件是一樣的,比如JdbcTemplate,RedisTemplate 等等,也是Spring 跟MyBatis 整合的最關鍵的一個類。

為什么不用DefaultSqlSession?它是線程不安全的,注意看類上的注解:

Note that this class is not Thread-Safe.

而SqlSessionTemplate 是線程安全的。

* Thread safe, Spring managed, {@code SqlSession} that works with Spring

回顧一下SqlSession 的生命周期:

對象生命周期
SqlSessionFactoryBuiler方法局部(method)
SqlSessionFactory(單例)應用級別(application)
SqlSession請求和操作(request/method)
Mapper方法(method)

在編程式的開發中,SqlSession 我們會在每次請求的時候創建一個,但是Spring里面只有一個SqlSessionTemplate(默認是單例的),多個線程同時調用的時候怎么保證線程安全?

思考:為什么SqlSessionTemplate 是線程安全的?

思考:在編程式的開發中,有什么方法保證SqlSession 的線程安全?

SqlSessionTemplate 里面有DefaultSqlSession 的所有的方法:selectOne()、selectList()、insert()、update()、delete(),不過它都是通過一個代理對象實現的。這個代理對象在構造方法里面通過一個代理類創建:

this.sqlSessionProxy = (SqlSession) newProxyInstance(SqlSessionFactory.class.getClassLoader(),new Class[] { SqlSession.class },new SqlSessionInterceptor());

所有的方法都會先走到內部代理類SqlSessionInterceptor 的invoke()方法:

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {SqlSession sqlSession = getSqlSession(SqlSessionTemplate.this.sqlSessionFactory,SqlSessionTemplate.this.executorType,SqlSessionTemplate.this.exceptionTranslator);try {Object result = method.invoke(sqlSession, args);

首先會使用工廠類、執行器類型、異常解析器創建一個sqlSession,然后再調用sqlSession 的實現類,實際上就是在這里調用了DefaultSqlSession 的方法。

?

總結

以上是生活随笔為你收集整理的MyBatis创建SqlSession可以直接使用DefaultSqlSession 吗?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。