02 June 2010

A note about Cascade.MERGE

Al salamo Alykom,

Hi folks, I've a long time since I've been posted about Java EE.
So, today we gonna talking about JPA, we are talking about the merge operation.

From Specs:

The semantics of the merge operation applied to an entity X are as follows:
- If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value cascade=MERGE or cascade=ALL annotation.

This is what I need to talk with you about:

Here' an example:
Consider we have a uni-directional many-to-one relationship between Jobs and the user that do that job:

public class User{
// .. user data here...

public class Job{

private User user;

public User getUser(){
return user;

as it appears, It is a uni-directional from Job to User (many-to-one)

suppose we have the following annotation over the getUser operation:

this means, when a managed Job have changed its User, on merging the Job Object to DB, also merge the in-relation Object (User).

Here's a code example that prove this specs element:

Job job = em.find(Job.class, 1);
User u = job.getUser();

After this code, the field name of User will be updated to be "mohammed".
Post a Comment