如果B出错,请回滚A.春季靴子,jdbctemplate [英] Roll back A if B goes wrong. spring boot, jdbctemplate
问题描述
我有一个方法"databaseChanges",它以迭代方式调用2个操作:A,B.首先是"A",最后是"B". 'A'& 'B'可以是 C 版本, U 日期 D 持久存储Oracle Database 11g中的功能.
I have a method, 'databaseChanges', which call 2 operations: A, B in iterative way. 'A' first, 'B' last. 'A' & 'B' can be Create, Update Delete functionalities in my persistent storage, Oracle Database 11g.
比方说
'A'更新表Users(属性zip,其中id = 1)中的一条记录.
'A' update a record in table Users, attribute zip, where id = 1.
'B'在表爱好中插入一条记录.
'B' insert a record in table hobbies.
场景::调用了databaseChanges方法,"A"操作并更新记录. "B"操作并尝试插入一条记录,发生了一些事情,引发了异常,该异常正在冒泡到databaseChanges方法中.
Scenario: databaseChanges method is been called, 'A' operates and update the record. 'B' operates and try to insert a record, something happen, an exception is been thrown, the exception is bubbling to the databaseChanges method.
预期:"A"和"B"没有任何变化. "A"所做的更新将被回滚. "B"什么也没变,嗯...有一个例外.
Expected: 'A' and 'B' didn't change nothing. the update which 'A' did, will be rollback. 'B' didn't changed nothing, well... there was an exception.
实际:"A"更新似乎没有被回滚. "B"什么也没变,嗯...有一个例外.
Actual: 'A' update seems to not been rolled back. 'B' didn't changed nothing, well... there was an exception.
某些代码
如果我有连接,我会做类似的事情:
If i had the connection, i would do something like:
private void databaseChanges(Connection conn) {
try {
conn.setAutoCommit(false);
A(); //update.
B(); //insert
conn.commit();
} catch (Exception e) {
try {
conn.rollback();
} catch (Exception ei) {
//logs...
}
} finally {
conn.setAutoCommit(true);
}
}
问题:我没有连接(请参阅问题所在的标签)
The problem: I don't have the connection (see the Tags that post with the question)
我试图:
@Service
public class SomeService implements ISomeService {
@Autowired
private NamedParameterJdbcTemplate jdbcTemplate;
@Autowired
private NamedParameterJdbcTemplate npjt;
@Transactional
private void databaseChanges() throws Exception {
A(); //update.
B(); //insert
}
}
我的AppConfig类:
My AppConfig class:
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
@Configuration
public class AppConfig {
@Autowired
private DataSource dataSource;
@Bean
public NamedParameterJdbcTemplate namedParameterJdbcTemplate() {
return new NamedParameterJdbcTemplate(dataSource);
}
}
'A'进行更新.从"B"引发了异常.由'A'进行的更新不会被回滚.
'A' makes the update. from 'B' an exception is been thrown. The update which been made by 'A' is not been rolled back.
从我阅读的内容中,我了解到我没有正确使用@Transactional. 我阅读并尝试了几篇博客文章和stackverflow Q&无法成功解决我的问题.
From what i read, i understand that i'm not using the @Transactional correctly. I read and tried several blogs posts and stackverflow Q & A without succeess to solve my problem.
有什么建议吗?
编辑
有一种方法可以调用databaseChanges()方法
There is a method that call databaseChanges() method
public void changes() throws Exception {
someLogicBefore();
databaseChanges();
someLogicAfter();
}
哪个方法应使用@Transactional注释
Which method should be annotated with @Transactional,
changes()? databaseChanges()?
changes()? databaseChanges()?
推荐答案
@Transactional
批注通过将对象包装在代理中而起作用,而代理又在事务中包装了用@Transactional
注释的方法.由于该注释不适用于私有方法(如您的示例),因为私有方法不能被继承 =>它们不能被包装(如果您将声明式事务与 aspectj ,则以下与代理相关的注意事项不适用).
@Transactional
annotation in spring works by wrapping your object in a proxy which in turn wraps methods annotated with @Transactional
in a transaction. Because of that annotation will not work on private methods (as in your example) because private methods can't be inherited => they can't be wrapped (this is not true if you use declarative transactions with aspectj, then proxy-related caveats below don't apply).
这是@Transactional
弹簧魔术的工作原理的基本说明.
Here is basic explanation of how @Transactional
spring magic works.
您写道:
class A {
@Transactional
public void method() {
}
}
但这是您注入豆子时实际得到的:
But this is what you actually get when you inject a bean:
class ProxiedA extends A {
private final A a;
public ProxiedA(A a) {
this.a = a;
}
@Override
public void method() {
try {
// open transaction ...
a.method();
// commit transaction
} catch (RuntimeException e) {
// rollback transaction
} catch (Exception e) {
// commit transaction
}
}
}
这有局限性.它们不能与@PostConstruct
方法一起使用,因为在代理对象之前调用它们.即使所有配置正确,默认情况下,事务也只会回滚 unchecked 异常.如果需要回退某些已检查的异常,请使用@Transactional(rollbackFor={CustomCheckedException.class})
.
This has limitations. They don't work with @PostConstruct
methods because they are called before object is proxied. And even if you configured all correctly, transactions are only rolled back on unchecked exceptions by default. Use @Transactional(rollbackFor={CustomCheckedException.class})
if you need rollback on some checked exception.
我知道的另一个经常遇到的警告:
Another frequently encountered caveat I know:
@Transactional
方法仅在您从外部"调用时才起作用,在下面的示例中,b()
将不会被包装在事务中:
@Transactional
method will only work if you call it "from outside", in following example b()
will not be wrapped in transaction:
class X {
public void a() {
b();
}
@Transactional
public void b() {
}
}
这也是因为@Transactional
通过代理对象起作用.在上面的示例中,a()
将调用X.b()
而不是增强的"spring proxy"方法b()
,因此将没有事务.解决方法是,必须从另一个bean调用b()
.
It is also because @Transactional
works by proxying your object. In example above a()
will call X.b()
not a enhanced "spring proxy" method b()
so there will be no transaction. As a workaround you have to call b()
from another bean.
遇到任何这些警告并且不能使用建议的解决方法(使方法为非私有方法或从另一个bean调用b()
)时,可以使用TransactionTemplate
代替声明式事务:
When you encountered any of these caveats and can't use a suggested workaround (make method non-private or call b()
from another bean) you can use TransactionTemplate
instead of declarative transactions:
public class A {
@Autowired
TransactionTemplate transactionTemplate;
public void method() {
transactionTemplate.execute(status -> {
A();
B();
return null;
});
}
...
}
更新
使用上面的信息回答OP更新的问题.
Answering to OP updated question using info above.
哪个方法应使用@Transactional进行注释: 变化()? databaseChanges()?
Which method should be annotated with @Transactional: changes()? databaseChanges()?
@Transactional(rollbackFor={Exception.class})
public void changes() throws Exception {
someLogicBefore();
databaseChanges();
someLogicAfter();
}
确保changes()
是从bean的外部调用的,而不是从类本身调用的,并且在实例化上下文之后(例如,这不是afterPropertiesSet()
或@PostConstruct
注释的方法).了解默认情况下,春季回滚事务仅适用于未检查的异常(尝试在rollbackFor检查的异常列表中更具体).
Make sure changes()
is called "from outside" of a bean, not from class itself and after context was instantiated (e.g. this is not afterPropertiesSet()
or @PostConstruct
annotated method). Understand that spring rollbacks transaction only for unchecked exceptions by default (try to be more specific in rollbackFor checked exceptions list).
这篇关于如果B出错,请回滚A.春季靴子,jdbctemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!