I am using Hibernate on a project and I am throughly confused on when to use org.hibernate.annotations.CascadeType and when to use javax.persistence.CascadeType annotations.
For instance when I should use something like this:
@OneToMany(fetch = FetchType.LAZY, cascade = javax.persistence.CascadeType.ALL)
vs something like this:
@OneToMany(fetch = FetchType.LAZY)
@Cascade(org.hibernate.annotations.CascadeType.ALL)
I have also read that hibernate will ignore certain cascade types that are in the one to xxxx annotations. Can someone set me straight?
CascadeType. MERGE propagates the merge operation from a parent to a child entity. Here, we can see that the merge operation first loads both address and person entities and then updates both as a result of CascadeType.
In JPA, if any operation is applied on an entity then it will perform on that particular entity only. These operations will not be applicable to the other entities that are related to it. To establish a dependency between related entities, JPA provides javax.
CascadeType. ALL specifies that when a Customer is created, if there is any Address association, then that Address will be created as well(CascadeType. PERSIST). If the Customer is deleted from persistence storage, the Address table will be deleted(CascadeType.
In general you'll find many examples of these kinds of overlapping when using Hibernate. There can be several different reasons for this. Either it's because of legacy reasons (Hibernate created the annotation before it got standardized in JPA), or it's because Hibernate supports more functionality than what the JPA standard allows, or it's because they only differ slightly in their semantics.
In this case, the Hibernate documentation is very clear of why @Cascade
exists when @OneToMany(cascade=...)
is the standard. The Hibernate annotation (@Cascade
) gives you many more options than the standard JPA one, and it also has slightly different semantics.
You should always prefer using the standard JPA annotations as long as you don't need some special Hibernate feature/semantics.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With