即使使用@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)也不会自动创建事务

amo*_*fis 0 jta java-ee java-ee-6

我的Java EE 6应用程序中有这样的托管bean:

@Named
@RequestScoped
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public class RegistrationBean implements Serializable {

    @PersistenceContext
    EntityManager em;

    public String doRegistration() {
        MyEntity entity = new MyEntity();
        em.persist(entity);
        return "view";
    }
}
Run Code Online (Sandbox Code Playgroud)

据我了解@TransactionAttribute,应自动创建新事务。但显然不是,因为我遇到了一个例外:javax.persistence.TransactionRequiredException: EntityManager must be access within a transaction

我的持久性单元具有transaction-type="JTA"属性。我正在使用JBoss 6 cr1。

Arj*_*jms 5

您尝试做的事情并不完全正确。您定义的是一个普通的CDI bean,它本身不支持@TransactionAttribute批注。该批注与EJB bean一起使用,您可以通过使用@Stateless批注获得该批注。

请注意,在这种情况下,您不一定需要使用TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)批注。默认情况下,在使用@Stateless注释bean时,您已经获取了TransactionAttributeType.REQUIRES,这在大多数情况下是您想要的。