java 如何在 EJB 中提交事务?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6483812/
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
how to commit a transaction in EJB?
提问by Muhammad Hewedy
I have the following scenario,
我有以下场景,
public void someEjbMethod1()
{
for (int i=0; i=10; i++)
{
em.merge(arr[i]);
em.flush();
}
}
I need to merge each object of (arr[i]
) separately. as the above code will commit all the arr[i]
instances at the end of the function.
我需要分别合并 ( arr[i]
) 的每个对象。因为上面的代码将arr[i]
在函数末尾提交所有实例。
I am thinking to do the following:
我正在考虑执行以下操作:
public void someEjbMethod1()
{
for (int i=0; i=10; i++)
{
saveObj(arr[i]);
}
}
// should I use a transaction attribute here??
public void saveObj(SomeObject obj)
{
em.merge(arr[i]);
em.flush();
}
回答by Vineet Reynolds
If you want container managed transactions, you may use the @TransactionAttribute with the value TransactionAttributeType.REQUIRES_NEWto annotate the saveObj
method as:
如果你想要容器管理的事务,你可以使用@TransactionAttribute 和值为 TransactionAttributeType.REQUIRES_NEW来注释该saveObj
方法:
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void saveObj(SomeObject obj)
{
...
}
This will ensure that a new transaction will be started for every invocation of the saveObj
method. The existing transaction associated with the someEjbMethod
will be suspended before every invocation of the saveObj
method. Every transaction started for the saveObj
method will be committed on return, and hence every entity will be updated in the database in it's own transaction.
这将确保每次调用该saveObj
方法都会启动一个新事务。与 关联的现有事务someEjbMethod
将在每次调用该saveObj
方法之前暂停。为该saveObj
方法启动的每个事务都将在返回时提交,因此每个实体都将在其自己的事务中的数据库中更新。