This error that I was dreaded of was "Deleted Entity Passed to Persist" error. This is not the type or name of the error. It is what Java revealed in the logs and it can't proceed because of the "Deleted Entity Passed to Persist". In the past, we noticed that it happened when we tried to remove an entity from database by using entityManager.remove(entityname). For those of you who have worked with EJB will know what entityManager is. Basically it's trying to delete a row of data from database and it's doing so by calling an API.
Let's say I have an entity called Person and a second entity called Credit Card. A person can have one or more credit cards. So, we created a one-to-many relationship between Person and Credit Card. Person has become a table in the database and Credit Card has become another table in the database. Credit Card table has a foreign key column called Person_Id which stores the Id of the person from Person table. We created two way relationship.
class Person{
@OneToMany
private List
//getter & setters etc.
}
class CreditCard{
@ManyToOne
private Person person;
}
We put one relationship in Person entity and another relationship in CreditCard entity. (Note: the above code is NOT complete, you will need to ask other annotations for it to work properly). By doing so, you will see two way relationship, i.e, if you look from Person entity, you will see it's connected to Credit Card entity and if you look from CreditCard entity, you will see it's connected to Person entity. Now if you want to delete a credit card record from the Credit Card table, you need to first take out the relationships between the Person and that Credit Card.
We used to set the Person Id to 'null' and then call the remove() method from the EntityManager. But doing so gives the above error.
I finally found out the solution that nullifying a column doesn't take out the relationship in this matter. Since this is two way relationship, we need to take out that credit card from the arrayList in the Person table. So instead of doing entityManager.remove(creditCard), we have to do this :
person.getCreditCards().remove(c); // c is a credit card
entityManger.remove(c);
This is also a proper way of removing entities. You should get no "deleted entity passed to persist" error by adding an additional line of code.
No comments:
Post a Comment