java 在方法上使用 @TransactionAttribute(value = TransactionAttributeType.NEVER)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6455225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:57:33  来源:igfitidea点击:

Using @TransactionAttribute(value = TransactionAttributeType.NEVER) on a method

javatransactionsannotationspersistenceejb

提问by Luke

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

.NEVER 属性表示它将保证该方法不会在事务内运行,但是对该方法内的其他方法的调用呢?

回答by Kris Babic

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.

在您提供的示例中,您可以从事务设置为 NEVER 的方法中调用需要事务的方法。在这种情况下,将为需要事务的方法调用创建一个新事务。如果内部方法标有 MANDATORY 设置,则内部方法调用将失败,因为现有事务不存在并且 MANDATORY 设置不会自动为您创建一个。