JPA Cascade remove

I am new to JPA / Hibernate. Currently 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 the save, the rows are inserted correctly in the parent and child table. However, when I try to delete, I get an error message -
10: 19: 35,465 ERROR [TxPolicy] javax.ejb.EJBTransactionRolledbackException: Deleting a single instance of com.data.entities.form.financial.CreditCard # 159?

I use a simple loop to determine the type of inheritance - CreditCard or DebitCard, and then call entityManager.remove (entity). What am I doing wrong?

Code to delete ..

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

Thanks.

WM

+4
source share
1 answer

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 permitted by EntityManager#remove(Object) . As described in java, it throws:

IllegalArgumentException - if not an entity or if a separate object

So you really need to re-bind the object before deleting it:

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

Or simply put:

 em.remove(em.merge(creditCard)); 
+7
source

Source: https://habr.com/ru/post/1308921/


All Articles