如何RollBack由@PersistenceContext注入的EntityManager的事务?

时间:2016-03-30 11:46:03

标签: java hibernate jpa jpa-2.0 hibernate-mapping

我正在使用JPA,我有一个抽象类,我注入我的entityManager,我有一个通用的方法,我将我的oject持久化到数据库,并在我的所有服务类扩展该抽象类但问题是:有时我有保持客户端和客户端的详细信息,但如果我在客户端的持久性中有异常,那么我的程序会保留客户端详细信息,这就是为什么我在查找持久性异常时要查找rollBack的原因。

我知道我可以像entityManager.getTransaction().rollback();那样做,但如果我管理我的实体经理,但在我的情况下,它由容器管理。

这是我的抽象类:

public abstract class AbstractEntityFactory<E>{
protected static final transient Logger LOGGER = CommonLogger.getLogger(AbstractEntityFactory.class);
@PersistenceContext(unitName = "Test_PU")
@Transient
@XmlTransient
private transient EntityManager entityManager;

public E persist(final E arg0) {
    LOGGER.debug("persist : Begin");
    this.getEntityManager().persist(arg0);
    this.getEntityManager().flush();
    LOGGER.debug("persist : End");
    return arg0;        
}

}

注意:我将Jboss EAP6作为服务器

3 个答案:

答案 0 :(得分:0)

您可以尝试使用UserTransaction.rollback回滚当前事务。

答案 1 :(得分:0)

因为您使用了&#34;容器&#34;。我猜你的意思是野生动物,... 在这种情况下,我假设您在某处使用@Transactional。此批注具有名为rollbackFor的属性。

如果我没记错,默认设置不会为RuntimeExceptions回滚。所以你可能会改变这个。

如果需要手动回滚,请使用UserTransaction。你应该能够通过

获得它
public class SomeBean {

    @Resource
    private UserTransaction transaction;
}

答案 2 :(得分:0)

you can use transaction rollback support annotation :

`    @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
    public E persist(final E arg0) {
    LOGGER.debug("persist : Begin");
    this.getEntityManager().persist(arg0);
    this.getEntityManager().flush();
    LOGGER.debug("persist : End");
    return arg0;        
}`