[英]Spring transaction doesn't rollback when switching to JDBCTemplate programmatically
我有一個用例,其中我需要從一個Oracle模式中獲取數據並將它們按表插入到另一個模式中。 為了進行讀寫,我通過JDBCTemplate使用了不同的數據源。 它們之間的切換是在代碼中完成的。 另外,我有一個Hibernate連接,用於從配置表中讀取數據。 這也是我的默認連接,它是在應用程序啟動時通過自動裝配設置的。 我正在使用Spring 4,Hibernate 4.3和Oracle 11。
對於JDBCTemplate,我有一個包含JDBCTemplate的抽象類,如下所示:
public abstract class GenericDao implements SystemChangedListener {
private NamedParameterJdbcTemplate jdbcTemplate;
/**
* Initializing the bean with the definition data source through @Autowired
* @param definitionDataSource as instance of @DataSource
*/
@Autowired
private void setDataSource(DataSource definitionDataSource) {
this.jdbcTemplate = new NamedParameterJdbcTemplate(definitionDataSource);
}
public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate(){
return this.jdbcTemplate;
}
@Override
public void updateDataSource(DataSource dataSource) {
this.setDataSource(dataSource);
}
}
當通過Service方法切換DataSource時,接口SystemChangedListener定義了updateDataSource方法,如下所示:
public class SystemServiceImpl implements SystemService, SystemChangable {
private List<GenericDao> daoList;
@Autowired
public void setDaoList(final List<GenericDao> daoList){
this.daoList = daoList;
}
@Override
public void notifyDaos(SystemDTO activeSystem) {
logger.debug("Notifying DAO of change in datasource...");
for(GenericDao dao : this.daoList){
dao.updateDataSource(activeSystem.getDataSource());
}
logger.debug("...done.");
}
@Override
public Boolean switchSystem(final SystemDTO toSystem) {
logger.info("Switching active system...");
notifyDaos(toSystem);
logger.info("Active system and datasource switched to: " + toSystem.getName());
return true;
}
}
到目前為止,該開關非常適合閱讀。 我可以毫無問題地在模式之間進行切換,但是如果由於某種原因在復制過程中出現異常,則事務不會回滾。
這是我的copyint方法:
@Transactional(rollbackFor = RuntimeException.class, propagation=Propagation.REQUIRED)
public void replicateSystem(String fromSystem, String toSystem) throws ApplicationException {
// FIXME: pass the user as information
// TODO: actually the method should take some model from the view and transform it in DTOs and stuff
StringBuffer protocolMessageBuf = new StringBuffer();
ReplicationProtocolEntryDTO replicationDTO = new ReplicationProtocolEntryDTO();
String userName = "xxx";
Date startTimeStamp = new Date();
try {
replicationStatusService.markRunningReplication();
List<ManagedTableReplicationDTO> replications = retrieveActiveManageTableReplications(fromSystem, toSystem);
protocolMessageBuf.append("Table count: ");
protocolMessageBuf.append(replications.size());
protocolMessageBuf.append(". ");
for (ManagedTableReplicationDTO repDTO : replications) {
protocolMessageBuf.append(repDTO.getTableToReplicate());
protocolMessageBuf.append(": ");
logger.info("Switching to source system: " + repDTO.getSourceSystem());
SystemDTO system = systemService.retrieveSystem(repDTO.getSourceSystem());
systemService.switchSystem(system);
ManagedTableDTO managedTable = managedTableService.retrieveAllManagedTableData(repDTO.getTableToReplicate());
protocolMessageBuf.append(managedTable.getRows() != null ? managedTable.getRows().size() : null);
protocolMessageBuf.append("; ");
ManagedTableUtils managedTableUtils = new ManagedTableUtils();
List<String> inserts = managedTableUtils.createTableInserts(managedTable);
logger.info("Switching to target system: " + repDTO.getSourceSystem());
SystemDTO targetSystem = systemService.retrieveSystem(repDTO.getTargetSystem());
systemService.switchSystem(targetSystem);
// TODO: what about constraints? foreign keys
logger.info("Cleaning up data in target table: " + repDTO.getTargetSystem());
managedTableService.cleanData(repDTO.getTableToReplicate());
/*
managedTableDao.deleteContents(repDTO.getTableToReplicate());
*/
// importing the data
managedTableService.importData(inserts);
/*
for (String insrt : inserts) {
managedTableDao.executeSqlInsert(insrt);
}
*/
protocolMessageBuf.append("Replication successful.");
}
} catch (ApplicationException ae) {
protocolMessageBuf.append("ERROR: ");
protocolMessageBuf.append(ae.getMessage());
throw new RuntimeException("Error replicating a table. Rollback.");
} finally {
replicationDTO = this.prepareProtocolRecord(userName, startTimeStamp, protocolMessageBuf.toString(), fromSystem, toSystem);
replicationProtocolService.writeProtocolEntry(replicationDTO);
replicationStatusService.markFinishedReplication();
}
}
我要做的是,檢索包含要復制其內容的表的列表,並循環執行,為它們生成插入語句,刪除目標表的內容,然后使用
public void executeSqlInsert(String insert) throws DataAccessException {
getNamedParameterJdbcTemplate().getJdbcOperations().execute(insert);
}
在這種情況下,將使用正確的數據源-目標系統的數據源。 例如,當在數據插入期間出現SQLException異常時,仍然會刪除數據並丟失目標表的數據。 我沒有異常的問題。 實際上,這是要求的一部分-所有異常都應進行協議化,如果有異常,則必須回滾整個復制過程。
這是我的db.xml:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<!-- Scans within the base package of the application for @Components to configure as beans -->
<bean id="placeholderConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:/db.properties" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:packagesToScan="de.telekom.cldb.admin"
p:dataSource-ref="dataSource"
p:jpaPropertyMap-ref="jpaPropertyMap"
p:jpaVendorAdapter-ref="hibernateVendor" />
<bean id="hibernateVendor" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="databasePlatform" value="${db.dialect}" />
</bean>
<!-- system 'definition' data source -->
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="${db.driver}"
p:url="${db.url}"
p:username="${db.username}"
p:password="${db.password}" />
<!--
p:maxActive="${dbcp.maxActive}"
p:maxIdle="${dbcp.maxIdle}"
p:maxWait="${dbcp.maxWait}"/>
-->
<util:map id="jpaPropertyMap">
<entry key="generateDdl" value="false"/>
<entry key="hibernate.hbm2ddl.auto" value="validate"/>
<entry key="hibernate.dialect" value="${db.dialect}"/>
<entry key="hibernate.default_schema" value="${db.schema}"/>
<entry key="hibernate.format_sql" value="false"/>
<entry key="hibernate.show_sql" value="true"/>
</util:map>
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- supports both JDBCTemplate connections and JPA -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
所以我的問題是交易不會回滾。 而且,在日志文件中我看不到任何線索,表明根本就沒有啟動trnsaction。 我究竟做錯了什么?
感謝您的幫助! 人
就像我在評論中說的那樣,默認情況下,spring框架在運行時(即未經檢查的異常)(任何包含RuntimeException
的子類的異常也包括在其中)中將事務標記為回滾。 另一方面,從事務方法生成的Checked異常不會觸發自動事務回滾。
為什么? 很簡單,因為我們了解到,檢查異常對於處理或拋出異常是必需的。 因此,就像您所做的那樣,將已檢查的異常從事務方法中拋出將告訴Spring框架(發生此拋出的異常,並且)您知道自己在做什么,從而導致框架跳過回滾部分。 如果發生未經檢查的異常,則將其視為錯誤或不良的異常處理,因此應回滾事務以避免數據損壞。
根據已檢查ApplicationException
的replicateSystem
方法的代碼, ApplicationException
不會觸發自動回滾。 因為發生異常時,客戶端(應用程序)有機會恢復。
根據Docs,應用程序異常是不會擴展RuntimeException的。
據我對EJB的了解,如果需要自動回滾事務,則可以使用@ApplicationException(rollback=true)
。
我不確定? 但我認為這是問題所在
// TODO: what about constraints? foreign keys
logger.info("Cleaning up data in target table: " + repDTO.getTargetSystem());
managedTableService.cleanData(repDTO.getTableToReplicate());
如果清除表時會拋出trunc some_table
那么此時Oracle提交事務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.