如何在EJB中提交事务

如何在EJB中提交事务

本文介绍了如何在EJB中提交事务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况,

public void someEjbMethod1()
{
    for (int i=0; i=10; i++)
    {
        em.merge(arr[i]);
        em.flush();
    }
}

我需要合并每个对象( arr [i] )。因为上述代码将在函数结尾处提交所有 arr [i] 实例。

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.

我是想要做以下事情:

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();
}


推荐答案

,您可以使用值为将 saveObj 方法注释为:

If you want container managed transactions, you may use the @TransactionAttribute with the value TransactionAttributeType.REQUIRES_NEW to annotate the saveObj method as:

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void saveObj(SomeObject obj)
{
    ...
}

这将确保每次调用 saveObj 方法时将启动一个新的事务。在每次调用 saveObj 方法之前,与 someEjbMethod 相关联的现有事务将被暂停。每个开始的事务都会在返回时提交给 saveObj 方法,因此每个实体将在数据库中自动更新。

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.

这篇关于如何在EJB中提交事务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 07:26