gpt4 book ai didi

java - 以编程方式切换到 JDBCTemplate 时 Spring 事务不会回滚

转载 作者:行者123 更新时间:2023-11-30 08:03:40 24 4
gpt4 key购买 nike

我有一个用例,其中我需要从一个 Oracle 模式获取数据并将它们逐个表插入到另一个模式。对于读取和写入,我通过 JDBCTemplate 使用不同的数据源。它们之间的切换是在代码内完成的。此外,我还有一个 Hibernate 连接,用于从配置表中读取数据。这也是我的默认连接,是应用程序启动时通过 Autowiring 设置的连接。我正在使用 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);
}
}

接口(interface) 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();
}
}

我所做的是,检索一个包含应复制其内容的表的列表,并在循环中为它们生成插入语句,删除目标表的内容并使用

执行插入
public void executeSqlInsert(String insert) throws DataAccessException {
getNamedParameterJdbcTemplate().getJdbcOperations().execute(insert);
}

在此使用正确的数据源 - 目标系统的数据源。例如,当插入数据期间出现 SQLException 时,数据的删除仍然会提交,并且目标表的数据会丢失。我对获得异常(exception)没有任何问题。事实上,这是要求的一部分 - 所有异常都应该得到协议(protocol),如果出现异常,整个复制过程必须回滚。

这是我的 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 子类的异常也包含在其中)。另一方面,事务方法生成的已检查异常不会触发自动事务回滚。

为什么?很简单,正如我们所知,检查异常对于处理或抛出是必要的(必须)。正如您所做的那样,从事务方法中抛出已检查的异常将告诉 spring 框架(发生了此抛出的异常并且)您知道自己在做什么,从而导致框架跳过回滚部分。如果出现未经检查的异常,则将其视为错误或错误的异常处理,因此回滚事务以避免数据损坏。

根据您已检查 ApplicationExceptionreplicateSystem 方法的代码,ApplicationException 不会触发自动回滚。因为当异常发生时客户端(应用程序)有机会恢复。

根据文档,应用程序异常是不扩展 RuntimeException 的。

根据我对 EJB 的了解,如果需要自动回滚事务,我们可以使用 @ApplicationException(rollback=true)

关于java - 以编程方式切换到 JDBCTemplate 时 Spring 事务不会回滚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31494514/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com