I am new to JPA/Hibernate. Currently开发者_JAVA技巧 using EJB3, Hibernate/JPA. I have an inheritacnce structure as follows..
@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.
}
When I add a row with save the rows are properly inserted into the parent and the child table. However when I try to delete I get an error -
10:19:35,465 ERROR [TxPolicy] javax.ejb.EJBTransactionRolledbackException: Removing a detached instance com.data.entities.form.financial.CreditCard#159?I am using a simple for loop to determine the inheritance type - CreditCard or DebitCard and then calling entityManager.remove(entity). What am I doing wrong?
Code for delete..
for(Form content: contents){
if(content.getType()==Type.CREDIT_CARD){
creditCardService.delete((CreditCard)content);
}
Thanks.
WM
The important part of the error is shown in bold below:
javax.ejb.EJBTransactionRolledbackException: Removing a detached instance com.data.entities.form.financial.CreditCard#159?
This is simply not allowed by the EntityManager#remove(Object)
operation. As java documented, it throws:
IllegalArgumentException
- if not an entity or if a detached entity
So you actually need to reattach the entity before to remove it:
CreditCard mergedCreditCard = em.merge(creditCard); // reattach the creditCard
em.remove(mergedCreditCard);
Or, more simply:
em.remove(em.merge(creditCard));
精彩评论