Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: How to use cascade in annotation?

How can I use cascade and annotations in hibernate?

But I stay with a doubt:

I have this situation:

public class Package(){
  @OneToOne(cascade=CascadeType.PERSIST)
  private Product product;

  @OneToOne(cascade=CascadeType.PERSIST)
  private User user;
  ..
}

When I try to session.save(package), an error occurs. I don't want to save product and package. I just want to initialize and set them into my package object.

Is that possible?

like image 434
Valter Silva Avatar asked Mar 01 '11 17:03

Valter Silva


People also ask

What is Cascade in Hibernate annotation?

Cascading is a feature in Hibernate, which is used to manage the state of the mapped entity whenever the state of its relationship owner (superclass) affected. When the relationship owner (superclass) is saved/ deleted, then the mapped entity associated with it should also be saved/ deleted automatically.

What is the use of Cascade in JPA?

Cascade Type PERSIST propagates the persist operation from a parent to a child entity. When we save the person entity, the address entity will also get saved.

What is Cascade CascadeType all in Hibernate?

The meaning of CascadeType. ALL is that the persistence will propagate (cascade) all EntityManager operations ( PERSIST, REMOVE, REFRESH, MERGE, DETACH ) to the relating entities. It seems in your case to be a bad idea, as removing an Address would lead to removing the related User .


1 Answers

See the hibernate documentation which is very clear on this issue. For instance you could use e.g.,

@Cascade(CascadeType.PERSIST)
private List<Object> obj;

or

@OneToMany(cascade = CascadeType.PERSIST)
private List<Object> obj;
like image 157
Johan Sjöberg Avatar answered Sep 19 '22 14:09

Johan Sjöberg