MySQL仍然在ejb事务回滚后提交

时间:2015-01-03 13:03:55

标签: java mysql jpa transactions ejb

我是EJB的新手,我注意到当ejb事务回滚时,MySQL错误地保留了我的实体。我实现了SessionSynchronization接口,以显式查看ejb事务的状态。以下是代码段:

@Entity
public class Fan implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public int id;

    public String name;

    @ManyToOne(cascade = CascadeType.PERSIST)
    public Singer favouriteSinger;
}

@Entity
public class Singer implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public int id;

    public String name;
}

@ApplicationException(rollback = true)
public class MyApplicationException extends RuntimeException { }

此ejb正在从另一个ejb(一个Web服务)调用:

@Stateful
public class HelloEJB implements HelloEJBLocal, SessionSynchronization {

    @PersistenceContext
    EntityManager entityManager;

    @Override
    public String testManyToOneUnidirectionalRelationship() {
        Singer singer = new Singer();
        Fan fan = new Fan();
        fan.favouriteSinger = singer;
        entityManager.persist(fan);

        // Test rollback behaviour
        exceptionalMethod();

        return "Created Singer:" + singer.id + " Fan:" + fan.id;
    }

    private void exceptionalMethod() {
        throw new MyApplicationException();
    }

    @Override
    public void afterBegin() throws EJBException, RemoteException {
        System.out.println(">>>>>>>>>> The container just created a new transaction");
    }

    @Override
    public void beforeCompletion() throws EJBException, RemoteException {
        System.out.println(">>>>>>>>>> The container is about to end a transaction");
    }

    @Override
    public void afterCompletion(boolean committed) throws EJBException, RemoteException {
        System.out.println(">>>>>>>>>> Transaction Status: " + (committed ? "Commited" : "Rolledback"));
    }
}

在调用'testManyToOneUnidirectionalRelationship'之后,我收到了'Transaction Status:Rolledback'消息,但仍发现Singer和Fan实体持久存在于MySQL数据库中。 请帮助解决这个问题。感谢

0 个答案:

没有答案