GionJh
GionJh

Reputation: 2894

Merge and lazy loading

Hi I hope you can help me with this question:

Student
...
@ManyToOne
Mentor


Mentor
...
@OneToMany
Student

Is there any difference in using merge on a student when:

Mentor is lazy: @ManyToOne(fetch=FetchType.LAZY,cascade = CascadeType.MERGE))

Mentor is eager: @ManyToOne(fetch=FetchType.EAGER,cascade = CascadeType.MERGE))

Upvotes: 1

Views: 1651

Answers (1)

Alexander Petrov
Alexander Petrov

Reputation: 9492

First nothing will happened when merging if you are not cascading. In your example you have not specified Cascade.Merge therefore your merge operation will not be cascaded.

Lets assume that you have cascading. If your entity is not initialized which may happen if you relationship is Lazy the cascading will not be propagated over the non initialized collection.

In your particular case following the JPA specification the default behavior of ManyToOne is EAGER.

In case it is EAGER the entity will be checked if it is dirty, in case it is dirty the merge will be cascaded further

One more thing. CascadeType.ALL on ManyToOne is a bad idea. Because if you DELETE one entity on the MANY side this will trigger a delete of the parent object. I believe you really dont want this. I strongly recommend you to remove the CascadeType.All

Upvotes: 2

Related Questions