交易中止

时间:2011-12-09 10:36:30

标签: java jpa

我的代码是这个..

@PersistenceContext(unitName = "myPU")
private EntityManager em;
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void registerManufactuerer(Manufacturer manufacturer) throws Exception {
    if (manufacturer.getId() != null) {
        for (Product product : manufacturer.getProducts()) {
            em.persist(product);
            em.remove(product);
        }
        em.persist(manufacturer);
        throw new Exception("Successfully registered");
    } else {
        throw new Exception("Registration is not possible");
    }
}

当我运行项目时,我得到了一个例外......那就是......

Caused by: javax.transaction.RollbackException: Transaction marked for rollback.
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:473)
at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:852)
at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5114)
... 63 more
Caused by: java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST: com.model.Product[ id=1 ].
    at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.discoverUnregisteredNewObjects(RepeatableWriteUnitOfWork.java:302)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.calculateChanges(UnitOfWorkImpl.java:695)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1482)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.issueSQLbeforeCompletion(UnitOfWorkImpl.java:3135)
    at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.issueSQLbeforeCompletion(RepeatableWriteUnitOfWork.java:344)
    at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:157)
    at org.eclipse.persistence.transaction.JTASynchronizationListener.beforeCompletion(JTASynchronizationListener.java:68)
    at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:435)
    ... 65 more
实际上......是什么原因?

1 个答案:

答案 0 :(得分:2)

原因是错误消息告诉您:

  

在同步过程中,通过未标记为级联的关系找到了一个新对象PERSIST:com.model.Product [id = 1]

您的产品引用了另一个尚未保留的实体,并且该关系未定义持久级联。因此,在数据库中找不到该新实体的ID,因此您的产品无法保留。

最有可能是制造商,所以请先坚持制造商。

是的,为什么你先坚持产品并立即再删除它?