Java進階學習第二十四天(Spring框架:事務管理、Spring與Hibernate整合)
一、事務控制
1、引入 使用者訪問 > Action > Service > Dao 如何保證: 在service中呼叫2次dao,其中一個dao執行失敗,整個操作要回滾
2、事務控制概述
① 程式設計式事務控制:自己手動控制事務
Jdbc程式碼: Conn.setAutoCommite(false); // 設定手動控制事務
Hibernate程式碼: Session.beginTransaction(); // 開啟一個事務
【細粒度的事務控制: 可以對指定的方法、指定的方法的某幾行新增事務控制】
特點:比較靈活,但開發起來比較繁瑣: 每次都要開啟、提交、回滾
② 宣告式事務控制
Spring提供了對事務的管理,這個就叫宣告式事務管理。
Spring提供了對事務控制的實現,使用者如果想用Spring的宣告式事務管理,只需要在配置檔案中配置即可; 不想使用時直接移除配置。這個實現了對事務控制的最大程度的解耦
Spring宣告式事務管理,核心實現就是基於Aop。
【粗粒度的事務控制: 只能給整個方法應用事務,不可以對方法的某幾行應用事務】(因為aop攔截的是方法)
Spring宣告式事務管理器類:
Jdbc技術:DataSourceTransactionManager
HibernateTransactionManager
3、宣告式事務管理(XML方式實現) 步驟: ① 引入spring-aop相關的4個jar檔案 ② 引入aop名稱空間 【XML配置方式需要引入】 ③ 引入tx名稱空間 【事務方式必須引入】
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 1. 資料來源物件: C3P0連線池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql:///hib_demo"></property> <property name="user" value="root"></property> <property name="password" value="root"></property> <property name="initialPoolSize" value="3"></property> <property name="maxPoolSize" value="10"></property> <property name="maxStatements" value="100"></property> <property name="acquireIncrement" value="2"></property> </bean> <!-- 2. JdbcTemplate工具類例項 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 3. dao例項 --> <bean id="deptDao" class="cn.itcast.a_tx.DeptDao"> <property name="jdbcTemplate" ref="jdbcTemplate"></property> </bean> <!-- 4. service例項 --> <bean id="deptService" class="cn.itcast.a_tx.DeptService"> <property name="deptDao" ref="deptDao"></property> </bean> <!-- #############5. Spring宣告式事務管理配置############### --> <!-- 5.1 配置事務管理器類 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 5.2 配置事務增強(如何管理事務)--> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="find*" read-only="true"/> <tx:method name="*" read-only="false"/> </tx:attributes> </tx:advice> <!-- 5.3 Aop配置: 攔截哪些方法(切入點表示式)+ 應用上面的事務增強配置 --> <aop:config> <aop:pointcut expression="execution(* cn.itcast.a_tx.DeptService.*())" id="pt"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/> </aop:config> </beans>
public class DeptDao { // 容器注入JdbcTemplate物件 private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public void save(Dept dept){ String sql = "insert into t_dept (deptName) values(?)"; jdbcTemplate.update(sql,dept.getDeptName()); } }
public class DeptService {
// 容器注入dao物件
private DeptDao deptDao;
public void setDeptDao(DeptDao deptDao) {
this.deptDao = deptDao;
}
/*
* 事務控制
*/
public void save(Dept dept){
// 第一次呼叫
deptDao.save(dept);
int i = 1/0; // 異常: 整個Service.save()執行成功的要回滾
// 第二次呼叫
deptDao.save(dept);
}
}
@Test
public void testApp() throws Exception {
//容器物件
ApplicationContext ac = new ClassPathXmlApplicationContext("cn/itcast/a_tx/bean.xml");
// 模擬資料
Dept dept = new Dept();
dept.setDeptName("測試: 開發部");
DeptService deptService = (DeptService) ac.getBean("deptService");
deptService.save(dept);
}
4、宣告式事務管理(註解方式實現) 使用註解實現Spring的宣告式事務管理,更加簡單! 步驟: ① 必須引入Aop相關的jar檔案 ② bean.xml中指定註解方式實現宣告式事務管理以及應用的事務管理器類 ③ 在需要新增事務控制的地方,寫上: @Transactional
@Transactional註解:
1)應用事務的註解
2)定義到方法上:當前方法應用spring的宣告式事務
3)定義到類上:當前類的所有的方法都應用Spring宣告式事務管理;
4)定義到父類上:當執行父類的方法時候應用事務
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 1. 資料來源物件: C3P0連線池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///hib_demo"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
<property name="initialPoolSize" value="3"></property>
<property name="maxPoolSize" value="10"></property>
<property name="maxStatements" value="100"></property>
<property name="acquireIncrement" value="2"></property>
</bean>
<!-- 2. JdbcTemplate工具類例項 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 事務管理器類 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 開啟註解掃描 -->
<context:component-scan base-package="cn.itcast.b_anno"></context:component-scan>
<!-- 註解方式實現事務: 指定是以註解方式實現事務 -->
<tx:annotation-driven transaction-manager="txManager"/>
<bean class="cn.itcast.b_anno.DeptDao"></bean>
</beans>
/**
* dao實現,使用Spring對jdbc支援功能
*/
@Repository
public class DeptDao {
@Resource
private JdbcTemplate jdbcTemplate;
public void save(Dept dept){
String sql = "insert into t_dept (deptName) values(?)";
jdbcTemplate.update(sql,dept.getDeptName());
}
}
// 測試: 日誌傳播行為
@Repository
public class LogDao {
@Resource
private JdbcTemplate jdbcTemplate;
// 始終開啟事務
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void insertLog() {
jdbcTemplate.update("insert into log_ values('在儲存Dept..')");
}
}
/**
* Service
*/
@Service
public class DeptService {
// 部門dao
@Resource
private DeptDao deptDao;
// 日誌dao
@Resource
private LogDao logDao;
/*
* 事務控制
*/
@Transactional(
readOnly = false, // 讀寫事務
timeout = -1, // 事務的超時時間不限制
//noRollbackFor = ArithmeticException.class, // 遇到數學異常不回滾
isolation = Isolation.DEFAULT, // 事務的隔離級別,資料庫的預設
propagation = Propagation.REQUIRED // 事務的傳播行為
)
public void save(Dept dept){
logDao.insertLog(); // 儲存日誌 【自己開啟一個事務】
int i = 1/0;
deptDao.save(dept); // 儲存部門
}
}
public class App {
@Test
public void testApp() throws Exception {
//容器物件
ApplicationContext ac = new ClassPathXmlApplicationContext("cn/itcast/b_anno/bean.xml");
// 模擬資料
Dept dept = new Dept();
dept.setDeptName("測試: 開發部");
DeptService deptService = (DeptService) ac.getBean("deptService");
deptService.save(dept);
}
// 瞭解容器的相關方法
@Test
public void testApp2() throws Exception {
//1. 根據bean.xml配置路徑,建立容器物件
//ApplicationContext ac = new ClassPathXmlApplicationContext("cn/itcast/b_anno/bean.xml");
//2. 根據多個配置檔案的路徑,建立容器物件
//ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{});
//3. 容器物件相關方法
ApplicationContext ac =
new ClassPathXmlApplicationContext("cn/itcast/b_anno/bean.xml");
//3.1 從容器中獲取指定名稱的bean物件
//DeptDao deptDao = (DeptDao) ac.getBean("deptDao");
//3.2 根據型別從容器獲取例項 【改型別只能在IOC中有唯一的物件,否則報錯】
//DeptDao deptDao = ac.getBean(DeptDao.class);
//3.3 泛型,不需要強轉
//DeptDao deptDao = ac.getBean("deptDap", DeptDao.class);
//3.4 獲取容器中bean物件的數量
//int count = ac.getBeanDefinitionCount();
String[] names = ac.getBeanDefinitionNames();
System.out.println(Arrays.toString(names));
}
}
5、事務屬性
@Transactional(
readOnly = false, // 讀寫事務
timeout = -1, // 事務的超時時間不限制
noRollbackFor = ArithmeticException.class, // 遇到數學異常不回滾
isolation = Isolation.DEFAULT, // 事務的隔離級別,資料庫的預設
propagation = Propagation.REQUIRED // 事務的傳播行為
)
6、事務傳播行為 ① Propagation.REQUIRED 指定當前的方法必須在事務的環境下執行; 如果當前執行的方法,已經存在事務, 就會加入當前的事務; ② Propagation.REQUIREDS_NEW 指定當前的方法必須在事務的環境下執行; 如果當前執行的方法,已經存在事務:事務會掛起; 會始終開啟一個新的事務,執行完後;剛才掛起的事務才繼續執行。
舉例:
Class Log{
Propagation.REQUIRED
insertLog();
}
Propagation.REQUIRED
Void saveDept(){
insertLog(); // 加入當前事務
.. 異常, 會回滾
saveDept();
}
Class Log{
Propagation.REQUIREDS_NEW
insertLog();
}
Propagation.REQUIRED
Void saveDept(){
insertLog(); // 始終開啟事務
.. 異常, 日誌不會回滾
saveDept();
}
二、Spring與Hibernate整合
1、Spring與Hibernate整合關鍵點 ① Hibernate的SessionFactory物件交給Spring建立 ② Hibernate事務交給spring的宣告式事務管理
2、SH整合步驟: ① 引入jar包 ◆ 連線池/資料庫驅動包 ◆ Hibernate相關jar ◆ Spring 核心包(5個) ◆ Spring aop 包(4個) ◆ spring-orm-3.2.5.RELEASE.jar 【spring對hibernate的支援】 ◆ spring-tx-3.2.5.RELEASE.jar 【事務相關】 ② 配置 ◆ hibernate.cfg.xml ◆ bean.xml ③ 搭建環境、單獨測試
3、步驟實現
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- dao 例項 -->
<bean id="deptDao" class="cn.itcast.dao.DeptDao">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- service 例項 -->
<bean id="deptService" class="cn.itcast.service.DeptService">
<property name="deptDao" ref="deptDao"></property>
</bean>
<!-- 資料來源配置 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///hib_demo"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
<property name="initialPoolSize" value="3"></property>
<property name="maxPoolSize" value="10"></property>
<property name="maxStatements" value="100"></property>
<property name="acquireIncrement" value="2"></property>
</bean>
<!-- ###########Spring與Hibernate整合 start########### -->
<!-- 方式(1)直接載入hibernate.cfg.xml檔案的方式整合
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean> -->
<!-- 方式(2)連線池交給spring管理 【一部分配置寫到hibernate中,一份分在spring中完成】
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
<property name="dataSource" ref="dataSource"></property>
</bean> -->
<!-- 【推薦】方式(3)所有的配置全部都在Spring配置檔案中完成 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 注入連線池物件 -->
<property name="dataSource" ref="dataSource"></property>
<!-- hibernate常用配置 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- hibernate對映配置
<property name="mappingLocations">
<list>
<value>classpath:cn/itcast/entity/*.hbm.xml</value>
</list>
</property>
-->
<property name="mappingDirectoryLocations">
<list>
<value>classpath:cn/itcast/entity/</value>
</list>
</property>
</bean>
<!-- ###########Spring與Hibernate整合 end########### -->
<!-- 事務配置 -->
<!-- a. 配置事務管理器類 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- b. 配置事務增強(攔截到方法後如果管理事務?) -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="*" read-only="false"/>
</tx:attributes>
</tx:advice>
<!-- c. Aop配置 -->
<aop:config>
<aop:pointcut expression="execution(* cn.itcast.service.*.*(..))" id="pt"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
</aop:config>
</beans>
// 資料訪問層
public class DeptDao {
// Spring與Hibernate整合: IOC容器注入
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
// 儲存一個記錄
// Spring與Hibernate整合:事務管理交給Spring
public void save(Dept dept) {
sessionFactory.getCurrentSession().save(dept);
}
}
public class DeptService {
private DeptDao deptDao;
public void setDeptDao(DeptDao deptDao) {
this.deptDao = deptDao;
}
public void save(Dept dept){
deptDao.save(dept);
}
}
public class App {
// 容器
private ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
@Test
public void testApp() throws Exception {
DeptService deptServie = (DeptService) ac.getBean("deptService");
System.out.println(deptServie.getClass());
deptServie.save(new Dept());
}
}