SqlSessionFactory SqlSessionFactory是單個資料庫映射關係經過編譯後的記憶體鏡像,主要作用是創建SqlSession。 InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml ...
SqlSessionFactory
SqlSessionFactory是單個資料庫映射關係經過編譯後的記憶體鏡像,主要作用是創建SqlSession。
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // Reader reader = Resources.getResourceAsReader("mybatis-config.xml"); // SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSessionFactory是線程安全的,一旦被創建,在整個應用程式執行期間都會存在。
創建SqlSessionFactory很消耗資料庫資源,如果多次創建同一資料庫的SqlSessionFactory,此資料庫的資源很容易被耗盡。
儘量使一個資料庫只對應一個SqlSessionFactory,構建SqlSessionFactory時,通常使用單例模式。
SqlSession
SqlSession底層封裝了JDBC連接,包含了大量的執行sql操作的方法,主要作用是執行持久化操作。
SqlSession是線程不安全的,每一個線程都應該有一個自己的SqlSession實例,並且該實例不能被共用。
SqlSession的使用範圍最好是一次請求或一個方法中,不要將SqlSession作為類的成員變數或者放到HttpSession等域中公用,使用完及時關閉。
SqlSession sqlSession=sqlSessionFactory.openSession(); try{ //執行持久化操作 }finally { sqlSession.close(); }
SqlSession常用的方法
- <T>T selectOne(String statement)
- <T>T selectOne(String statement, Object param)
只能返回0條或1條記錄,若返回多條記錄,會拋出異常。
- <E>List<E> selectList(String statement)
- <E>List<E> selectList(String statement, Object param)
- <E>List<E> selectList(String statement, Object param, RowBounds rowBounds) //rowBounds用於分頁
可以返回0條或多條記錄(數量不受限制)。
- void select(String statement, Object param, ResultHandler handler) //handler指定結果集的處理方式
註意返回值是void,使用handler指定的方式處理結果集,常用於比較複雜的結果集,比如多表查詢。
- int insert | update | delete(String statement)
- int insert | update | delete(String statement, Object param)
返回受影響的記錄數。
- void commit() //提交事務(本次session期間做的改動)
- void rollback() //回滾事務
- void close() //關閉SqlSession對象
- <T>T getMapper(Class<T> type) //返回Mapper介面的代理對象
該對象關聯了SqlSession對象,可通過該對象直接操作資料庫,mybatis官方推薦使用Mapper對象操作資料庫。參數type是Mapper介面的class對象。
getMapper()的用法可參考:https://www.cnblogs.com/chy18883701161/p/12152695.html
selectList()使用示例
<select id="queryById" parameterType="Integer" resultType="com.chy.pojo.Student"> SELECT * FROM student_tb WHERE id>#{id} </select>
List<Student> list = sqlSession.selectList("queryById", 5);
返回值類型是寫POJO類,不是寫List。
mybatis會根據結果集中的記錄數來判斷,如果只有一條記錄,映射為Student對象,如果有多條記錄,映射為List<Student>。
分頁:只取結果集的一部分記錄。
//參數:結果集中的記錄的下標,要取的記錄數 RowBounds rowBounds = new RowBounds(1, 3); List<Student> list = sqlSession.selectList("queryById", 5, rowBounds);
只將結果集的第2、3、4條記錄取出來,映射到list中。
附 MyBatis常用的工具類
public class MyBatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }