在方法上使用 @TransactionAttribute(value = TransactionAttributeType.NEVER)
您可以在不需要事务的方法中调用需要事务的方法吗?
@TransactionAttribute(value = TransactionAttributeType.NEVER)
public void DoSomething(final List<Item> items) {
//can you call a method that requires a transaction here ?
for (Item i : items) {
methodCall(item);
}
@TransactionAttribute(value = TransactionAttributeType.REQUIRES_NEW)
public void methodCall(final Item item) {
// access lazily loaded item properties
item.getSalesOrder();
item.getAllocation();
//throws org.hibernate.LazyInitializationException: could not initialize proxy - no Session
}
.NEVER 属性表示它将保证该方法不会在事务内运行,但是调用该方法内的其他方法又如何呢?
Can you call a method that requires a transaction inside a method that does not?
@TransactionAttribute(value = TransactionAttributeType.NEVER)
public void DoSomething(final List<Item> items) {
//can you call a method that requires a transaction here ?
for (Item i : items) {
methodCall(item);
}
@TransactionAttribute(value = TransactionAttributeType.REQUIRES_NEW)
public void methodCall(final Item item) {
// access lazily loaded item properties
item.getSalesOrder();
item.getAllocation();
//throws org.hibernate.LazyInitializationException: could not initialize proxy - no Session
}
The .NEVER attribute says it will guarantee the method does not run inside a transaction but what about calls to other methods inside that method
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
注解仅定义调用注解方法时必须存在的所需事务状态(在这种情况下,事务必须不存在)。它不限制注释方法执行过程中可能发生的情况。因此,在这种方法中,您可以毫无问题地开始新交易。
在您提供的示例中,您可以调用一个需要从事务设置为 NEVER 的方法内进行事务的方法。在这种情况下,将为需要事务的方法调用创建一个新事务。如果内部方法标记有 MANDATORY 设置,则内部方法调用将失败,因为现有事务不存在,并且 MANDATORY 设置不会自动为您创建事务。
The annotation only defines the required transaction state which must exist when the annotated method is invoked (in this case a transaction must not exist). It does not restrict what may occur within the execution of the annotation method. So within this method you could start a new transaction without any problem.
In the example that you provided, you may call a method which requires a transaction from within a method that has a transactional setting of NEVER. In this situation, a new transaction will be created for the method call that requires the transaction. If the inner method is marked with a MANDATORY setting, then the inner method call will fail as an existing transaction does not exist and the MANDATORY setting does not automatically create one for you.