Reputation: 1222
I have read the cascade type definitions multiple times but i just cannot get my head around which one to use for the particular case i am trying to implement.
I have @OneToMany
relationship between the Worker
class and Task
class, so worker
can have multiple tasks but each Task
is only for one Worker
private List <Task> tasks
holds the tasks in the Worker
class and
private Worker worker;
is the Worker
object in the Task
class
I am stuck at the ?
below, don't know which cascade type i should use.
@OneToMany(targetEntity=Task.class, mappedBy="worker", cascade=CascadeType.?, fetch = FetchType.LAZY)
Both objects should exist without one another but i want the changes to Task
objects to reflect on the Worker
object and vice versa
Ultimately(if i can get this to work :) ) i am suppose to write an algorithm to match the best worker when a new task get entered to the system i want to know if i am on the right track or not. Thanks
Upvotes: 3
Views: 6407
Reputation: 1582
This depends on how you are using your entities.
CascadeType.DETACH
. If you do, then you should probably include this CascadeType
.CascadeType.PERSIST
is usually a good choice and you can't really go wrong with this one. But like above: It doesn't sound like you are creating a worker and a new task in the same process. But if you do, then choose this CascadeType
.CascadeType.REMOVE
from what I understand.Upvotes: 3
Reputation: 32155
Well in your specific case you want to revert changes in one entity to the other side and you don't want to remove it if the mapping entity is removed, to answer both your requirements:
Both objects should exist without one another
In that case you should not use CascadeType.REMOVE
type because it emoves all related entities association with this setting when the owning entity is deleted.
but i want the changes to
Task
objects to reflect on theWorker
In that case using the CascadeType.PERSIST
and CascadeType.MERGE
types will be sufficient to reflect changes between both sides as CascadeType.PERSIST
covers both save()
and persist()
operations while CascadeType.MERGE
will handle the merge()
operation.
For further details about this topic I suggest reading HowToDoInJava Hibernate JPA Cascade Types article as it briefly illustartes all these cases.
Upvotes: 4