Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate and JPA cascade types when to use which one and where

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?

like image 964
Jimmy Johnson Avatar asked Dec 28 '12 07:12

Jimmy Johnson


People also ask

What is the use of Cascade types in Hibernate?

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.

What is the use of Cascade in JPA?

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.

Why we use Cascade CascadeType all?

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.


1 Answers

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.

like image 144
Aleksander Blomskøld Avatar answered Sep 17 '22 18:09

Aleksander Blomskøld