JPA Cascade删除

时间:2010-05-05 17:45:31

标签: java hibernate orm jpa multiple-inheritance

我是JPA / Hibernate的新手。目前使用EJB3,Hibernate / JPA。我有一个继承结构如下..


@Entity
@DiscriminatorColumn(name = "form_type")
@Inheritance(strategy = InheritanceType.JOINED)
@GenericGenerator(name = "FORMS_SEQ", strategy = "sequence-identity", parameters = @Parameter(name = "sequence", value = "FORMS_SEQ"))
@Table(name = "Forms")
public abstract class Form{
    //code for Form
}

@Entity
@Table(name = "CREDIT_CARDS")
@PrimaryKeyJoinColumn(name="CREDIT_CARD_ID")
public class CreditCardForm extends Form {
       //Code for CreditCards.
}

当我添加一行保存时,行正确地插入到父表和子表中。但是,当我尝试删除时,我收到错误 -
10:19:35,465 ERROR [TxPolicy] javax.ejb.EJBTransactionRolledbackException:删除分离的实例com.data.entities.form.financial.CreditCard#159?

我使用一个简单的for循环来确定继承类型 - CreditCard或DebitCard,然后调用entityManager.remove(entity)。我做错了什么?

删除代码..

for(Form content: contents){
  if(content.getType()==Type.CREDIT_CARD){
     creditCardService.delete((CreditCard)content);
  }

感谢。

WM

1 个答案:

答案 0 :(得分:7)

错误的重要部分如下面的粗体显示:

javax.ejb.EJBTransactionRolledbackException: Removing a detached instance com.data.entities.form.financial.CreditCard#159?

EntityManager#remove(Object)操作根本不允许这样做。正如java记录的那样,它抛出:

  

IllegalArgumentException - 如果不是实体或,如果是分离的实体

因此,您实际上需要在删除之前重新附加实体:

CreditCard mergedCreditCard = em.merge(creditCard); // reattach the creditCard
em.remove(mergedCreditCard);

或者更简单:

em.remove(em.merge(creditCard));