Spring 以编程方式切换到 JDBCTemplate 时事务不会回滚
Spring transaction doesn't rollback when switching to JDBCTemplate programmatically
我有这个用例,我需要从一个 Oracle 模式获取数据并将它们插入另一个模式,table by table。对于阅读和写作,我通过 JDBCTemplate 使用不同的数据源。它们之间的切换是在代码中完成的。此外,我还有一个 Hibernate 连接,用于从配置 tables 中读取数据。这也是我的默认连接,在应用程序启动时通过自动装配设置的连接。我正在使用 Spring 4、Hibernate 4.3 和 Oracle 11。
对于 JDBCTemplate,我有一个包含 JDBCTemplate 的抽象 class,如下所示:
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);
}
}
SystemChangedListener 接口定义了 updateDataSource 方法,当通过 Service 方法切换 DataSource 时调用该方法,如下所示:
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();
}
}
我所做的是,我检索一个包含 tables 的列表,其内容应该被复制并在一个循环中,为它们生成插入语句,删除目标 table 的内容并执行
的插入
public void executeSqlInsert(String insert) throws DataAccessException {
getNamedParameterJdbcTemplate().getJdbcOperations().execute(insert);
}
在此使用了正确的数据源 - 目标系统的数据源。例如,当在插入数据的过程中某处出现 SQLException 时,数据的删除仍然被提交并且目标 table 的数据丢失。我对获得例外没有问题。事实上,这是要求的一部分——所有的异常都应该得到协议,如果有异常,整个复制过程必须回滚。
这是我的 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>
所以我的问题是事务没有回滚。而且,我在日志文件中没有看到任何线索,根本没有启动交易。我究竟做错了什么?
感谢您的帮助!
阿尔
我不确定?但我觉得问题就在这一点
// TODO: what about constraints? foreign keys
logger.info("Cleaning up data in target table: " + repDTO.getTargetSystem());
managedTableService.cleanData(repDTO.getTableToReplicate());
如果表的清除抛出 trunc some_table
那么此时 Oracle 提交事务。
正如我在评论中所说,默认情况下,spring 框架在运行时将事务标记为回滚,即未经检查的异常(任何属于 RuntimeException
的子类的异常也包含在这个)。另一方面,从事务方法生成的已检查异常不会触发自动事务回滚。
为什么?很简单,正如我们所了解的,检查异常对于处理或抛出是必要的(必须)。因此,就像您所做的那样,从事务方法中抛出已检查的异常将告诉 spring 框架(发生了此抛出的异常并且)您知道自己在做什么,从而使框架跳过回滚部分。在未经检查的异常情况下,它被认为是错误或错误的异常处理,因此回滚事务以避免数据损坏。
根据您已检查 ApplicationException
的 replicateSystem
方法代码,ApplicationException
不会触发自动回滚。因为当异常发生时,客户端(应用程序)有机会恢复。
根据文档,应用程序异常是不扩展 RuntimeException 的。
根据我对 EJB 的了解,如果需要自动回滚事务,我们可以使用 @ApplicationException(rollback=true)
。
我有这个用例,我需要从一个 Oracle 模式获取数据并将它们插入另一个模式,table by table。对于阅读和写作,我通过 JDBCTemplate 使用不同的数据源。它们之间的切换是在代码中完成的。此外,我还有一个 Hibernate 连接,用于从配置 tables 中读取数据。这也是我的默认连接,在应用程序启动时通过自动装配设置的连接。我正在使用 Spring 4、Hibernate 4.3 和 Oracle 11。
对于 JDBCTemplate,我有一个包含 JDBCTemplate 的抽象 class,如下所示:
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);
}
}
SystemChangedListener 接口定义了 updateDataSource 方法,当通过 Service 方法切换 DataSource 时调用该方法,如下所示:
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();
}
}
我所做的是,我检索一个包含 tables 的列表,其内容应该被复制并在一个循环中,为它们生成插入语句,删除目标 table 的内容并执行
的插入public void executeSqlInsert(String insert) throws DataAccessException {
getNamedParameterJdbcTemplate().getJdbcOperations().execute(insert);
}
在此使用了正确的数据源 - 目标系统的数据源。例如,当在插入数据的过程中某处出现 SQLException 时,数据的删除仍然被提交并且目标 table 的数据丢失。我对获得例外没有问题。事实上,这是要求的一部分——所有的异常都应该得到协议,如果有异常,整个复制过程必须回滚。
这是我的 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>
所以我的问题是事务没有回滚。而且,我在日志文件中没有看到任何线索,根本没有启动交易。我究竟做错了什么?
感谢您的帮助! 阿尔
我不确定?但我觉得问题就在这一点
// TODO: what about constraints? foreign keys
logger.info("Cleaning up data in target table: " + repDTO.getTargetSystem());
managedTableService.cleanData(repDTO.getTableToReplicate());
如果表的清除抛出 trunc some_table
那么此时 Oracle 提交事务。
正如我在评论中所说,默认情况下,spring 框架在运行时将事务标记为回滚,即未经检查的异常(任何属于 RuntimeException
的子类的异常也包含在这个)。另一方面,从事务方法生成的已检查异常不会触发自动事务回滚。
为什么?很简单,正如我们所了解的,检查异常对于处理或抛出是必要的(必须)。因此,就像您所做的那样,从事务方法中抛出已检查的异常将告诉 spring 框架(发生了此抛出的异常并且)您知道自己在做什么,从而使框架跳过回滚部分。在未经检查的异常情况下,它被认为是错误或错误的异常处理,因此回滚事务以避免数据损坏。
根据您已检查 ApplicationException
的 replicateSystem
方法代码,ApplicationException
不会触发自动回滚。因为当异常发生时,客户端(应用程序)有机会恢复。
根据文档,应用程序异常是不扩展 RuntimeException 的。
根据我对 EJB 的了解,如果需要自动回滚事务,我们可以使用 @ApplicationException(rollback=true)
。