Cascade.Merge of child records in JPA

View: New views
3 Messages — Rating Filter:   Alert me  

Cascade.Merge of child records in JPA

by chandana78 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi,
Anybody has any experience with merging child records with an already existing collection of records? Does JPA do it automatically?

Here is the scenario.

Lets say I've US country as the parent entity and I've as child entities a few states, VA and MD. If I want to add more states to US, automatic merging works fine.

Old: US -> VA, MD
New: US -> VA, MD + DE = VA, MD, DE.  This works fine.

Old: US -> VA, MD
New: US -> VA, MD - MD = VA (Expected)
                       = VA, MD (actual)

To put it simply, with cascaded merge, additions work fine, deletions don't.

And to Make it more confusing, my unit test works perfectly with deletions, but the actual backend call doesn't give me the correct result through the UI.

I am using container based transactions and the service method uses @Transactional annotation.

Pseudocode:
_______________________________________________________

@Transactional
public ServiceClass{

public void update(Parent newParentPOJO){
   print parentEntity.getChildren().getSize();   // Prints 5

   parentEntity = getUpdatedEntityFromTheUI();
   parentEntity = entityManager.merge(entity);
   entityManager.flush();

    parentEntity = entityManager.find(parentEntity.class, id);
    print parentEntity.getChildren().getSize();   // Prints 3,    correct value

    }
}
_______________________________________________________

So, the actual backend call also works fine inside the method, but persisting that whenever the transaction is committed doesn't happen.

Thanks,
Chandana
 

Re: Cascade.Merge of child records in JPA

by James Sutherland :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

My guess is this has nothing to do with merge, but with remove.

To have an object removed from the database, you need to call remove() on it.
Merge will remove it from the collection, but you must call remove() to have it removed from the database.  Even if you set cascade remove, you still must call remove (cascade remove only cascades the remove operation).

In JPA 2.0 there will be a remove orphans option to handle this.  EclipseLink also provides an @PrivateOwned option for this.

Re: Cascade.Merge of child records in JPA

by chandana78 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Thanks for your reply.