Chitika

Tuesday, January 6, 2015

Spring MVC Hibernate entity update

Following is the steps involved in updating an entity, in Spring MVC:

function(Entity ent) {
....
// where ent is the entity passed through spring mvc.

1. First get entity from repo
   Entity savedEntity = repo.getById(entId);

2. Merge savedEntity with ent passed from spring MVC
    savedEntity.setA(ent.getA());
    savedEntity.setB(ent.getB());
    // store last field going to delete, do not delete it yet (if any)
    Ent2 ent = savedEntity.getEnt2();
    // repopulate with new field
    savedEntity.setEnt2(new Ent2());

3. Save (update) entity
    repo.save(savedEntity);

4. Delete last field (if any), from step 2
    repoEnt2.delete(ent);

Not following above step will result in following exceptions:

org.hibernate.ObjectDeletedException: deleted instance passed to merge.
java.lang.IllegalStateException: An entity copy was already assigned to a different entity.

No comments:

Post a Comment