Spring:Propagation.REQUIRED无效 [英] Spring:Propagation.REQUIRED not working
问题描述
我在几个表中插入记录,即 Dept
和 Emp
。如果 Dept
表成功创建,那么我只想在 Emp
表中插入记录。此外,如果 Emp
中的任何插入失败,那么我想回滚所有包含来自 Emp
以及部门
表。
I am inserting records in a couple of tables namely Dept
and Emp
. If the Dept
table is successfully created then only I want to insert records in Emp
table. Also, if any of the insert in Emp
fails, then I want to rollback all the transaction which includes both rollback from Emp
as well as Dept
tables.
我尝试使用 Propagation.REQUIRED
如下所示:
Java文件
public void saveEmployee(Employee empl){
try {
jdbcTemplate.update("INSERT INTO EMP VALUES(?,?,?,?,?)",empl.getEmpId(),empl.getEmpName(),
empl.getDeptId(),empl.getAge(),empl.getSex());
} catch (DataAccessException e) {
e.printStackTrace();
}
}
@Transactional(propagation=Propagation.REQUIRED)
public void saveRecords(){
saveDepartment(dept);
saveEmployee(empl);
}
context.xml
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
问题:
即使 Emp
表中的插入失败, Dept
插入也会被保留,我不想要。我想要回滚所有内容。
Even if an insertion in Emp
table fails, the Dept
insertion is getting persisted which I don't want. I want to rollback everything.
请建议。
推荐答案
问题是你的陷阱。由于捕获了异常,因此tx不会回滚。
The problem is your catch block. Since the exception is catched the tx don't rollback.
您必须抛出异常:
public void saveEmployee(Employee empl){
try {
jdbcTemplate.update("INSERT INTO EMP VALUES(?,?,?,?,?)",empl.getEmpId(),empl.getEmpName(),
empl.getDeptId(),empl.getAge(),empl.getSex());
} catch (DataAccessException e) {
e.printStackTrace();
throw e;
}
}
顺便提一下,语义 Progation.Required 只是意味着:如果不存在则创建一个新的tx或者如果有tx正在运行则使用现有的。
And by the way, the semantic of Progation.Required just means : create a new tx if it don't exists OR use an existing one if there is tx running.
在您的评论之后,建议您查看NEW tx的效果:
Following your comment here is a suggestion to see the effect of NEW tx :
@Transactional(propagation=Propagation.REQUIRES_NEW)
public void saveEmployee(Employee empl){
try {
jdbcTemplate.update("INSERT INTO EMP VALUES(?,?,?,?,?)",empl.getEmpId(),empl.getEmpName(),
empl.getDeptId(),empl.getAge(),empl.getSex());
} catch (DataAccessException e) {
e.printStackTrace();
throw e;
}
}
@Transactional(propagation=Propagation.REQUIRED)
public void saveRecords(){
saveDepartment(dept);
try{
saveEmployee(empl);
}catch(Exception e){Logger.log("Fail to save emp !");}
}
查看REQUIRES_NEW效果的关键是捕获saveEmployee周围的异常。如果你没有捕获它:异常将在另一个tx(在输入saveRecords()时启动的那个)传播,它也会回滚。
The key point to see the effect of REQUIRES_NEW is to catch the exception around saveEmployee. If you don't catch it : the exception will propagate in the other tx (the one started when entering saveRecords() ) and it will rollback too.
这篇关于Spring:Propagation.REQUIRED无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!