06_關於SqlSession


一.SqlSession適用范圍

(1).SqlSessionFactoryBuilder

通過SqlSessionFactoryBuilder創建會話工廠SqlSessionFactory

將SqlSessionFactoryBuilder當成一個工具類使用,無需單例模式管理SqlSessionFactoryBuilder。

在需要創建SqlSessionFactory時,只需new一次SqlSessionFactoryBuilder即可。

 //mybatis配置文件
 String resource="SqlMapConfig.xml";
       
 //得到配置文件
 InputStream inputStream=Resources.getResourceAsStream(resource);
        
//創建會話工廠,傳入mybatis的配置文件信息
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);

(2)SqlSessionFactory

通過SqlSessionFactory創建SqlSession,使用單例模式管理SqlSessionFactory(工廠一旦創建,使用一個單例)

(MyBatis與Spring整合后,使用單例模式管理SqlSessionFactory)

//通過工廠得到SqlSession
SqlSession sqlSession=sqlSessionFactory.openSession();

(3)SqlSession

SqlSession是一個面向用戶(軟件工程師)的接口。

SqlSession中提供了許多操縱數據庫的方法,如:

selectOne():返回單個對象

selectList():返回當個或多個對象

.....

SqlSession是線程不安全的,在SqlSession實現類中除了接口中的方法(操作數據庫的方法),還有數據域屬性。

SqlSession最佳應用場合在方法體內,定義成局部變量使用。

//通過SqlSession操作數據庫
//第一個參數:映射文件中statement的id,等於:namespace+"."+statement的id
//第二個參數:指定映射文件中的所匹配的parameterType類型的參數
User user=sqlSession.selectOne("test.findUserById", 2);
//刪除用戶
sqlSession.delete("test.deleteUserById",2);
//插入數據,后返回id
sqlSession.insert("test.insertUserReturnId",user);
//更新數據
sqlSession.update("test.updateUserById",user);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM