天天看點

Mybatis(三)、mybatis執行示例和mybatis事務以及緩存跟二級緩存簡單了解

一、Mybatis在控制台程式中的示範示例

1、建立sqlSession資料庫語句執行對象

Reader reader=Resources.getResourceAsReader("resourse.xml");
		SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
		SqlSession sqlSession=sqlSessionFactory.openSession();
           

2、執行sql查詢

StudentEntity studentEntity=new StudentEntity();
		studentEntity.setS_name("小");
		studentEntity.setS_age(18);
		List list=sqlSession.selectList("dynamicSelect3", studentEntity);
		System.out.println(list.size());
           

3、結果周遊輸出到控制台

for(int i=0;i<list.size();i++){
		StudentEntity student2=(StudentEntity) list.get(i);
		System.out.println("s_name名稱"+student2.getS_name());
	}
           

二、mybatis事務

在新增操作的時候,預設是需要使用sqlSession.commit();來向資料庫送出資料,不然新增的資料隻送出到了緩存裡面,并沒有完成資料庫資料的新增。

代碼見以下示例:

StudentEntity student4=new StudentEntity();
		String s_name="小澤瑪利亞";
		student4.setS_name(s_name);
		student4.setS_age(18);
		student4.setS_id(UUID.randomUUID().toString().replace("-", ""));
		student4.setS_loginName("132");
		student4.setS_passWord("123456");
		sqlSession.insert("insert",student4);
		sqlSession.commit();
           

三、mybatis緩存機制簡單介紹

1、一級緩存

mybatis在建立SQLSession對象的時候就預設開啟了以及緩存,當SQLSession關閉或者執行清空緩存時,緩存會清空,此時将不能再使用上一次執行的操作緩存。

也就是說,如果在兩次相同的查詢中間執行了緩存清空,第二次查詢就無法從緩存裡面使用第一次查詢的結果。

2、二級緩存

在二級緩存使用時,需要在實體類的配置檔案裡面配置<cache>标簽。

檢視mybatis詳細資訊的童鞋請移步:《深入了解mybatis原理》 MyBatis的一級緩存實作詳解 及使用注意事項