13

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?

Siamak
  • 335
  • 1
  • 11
Valter Silva
  • 16,446
  • 52
  • 137
  • 218
  • Your question has no context - please add an example of what you're specifically trying to accomplish. Also, if you need to add more information, it would be better to update your question itself (instead of using comments). Click the `edit` button under the question tags. – Rob Hruska Mar 01 '11 at 17:39
  • Hi Rob, how can i use a [code][/code] in this website ? – Valter Silva Mar 01 '11 at 17:44
  • When you edit your question, there's an icon above the text area that looks like `{}`. You can select your code and click that button to format it. Alternatively, you can indent all of the code four spaces. Thanks for updating your question with more information. – Rob Hruska Mar 01 '11 at 17:45
  • It's me who says thanks Rob, thank you ! – Valter Silva Mar 01 '11 at 17:47
  • 2
    To your new question: `CascadeType.PERSIST` means when you save `product` your `user` will be saved with it. If you want to **initialize on read** you should set `FetchType.EAGER` or perform a `HQL` query with `left join` etc. Also, don't edit a question into a different question, and if you are, provide a clear **update** instead. – Johan Sjöberg Mar 01 '11 at 17:48
  • @Johan - I don't think he edited a new question in; I think he was just a bit vague/unclear when he initially asked. – Rob Hruska Mar 01 '11 at 17:52

2 Answers2

17

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;
Johan Sjöberg
  • 47,929
  • 21
  • 130
  • 148
  • What is the first alternative for "SAVE_UPDATE" on the second one? – JaskeyLam Sep 15 '15 at 04:33
  • @Jaskey I may be wrong but PERSIST persists detached object when SAVE_UPDATE first tries to seek this detached object in database and if succeed only updates it, otherwise works as PERSIST. – jjpikoov May 31 '16 at 09:47
1

If you use the hibernate native API , then you should use the annotation of hibernate for cascade and it is :

@Cascade(CascadeType.SAVED_UPDATE)

then you call save() method but with your annotation , you should call the method persist() of the JPA

Hamdi Baligh
  • 874
  • 1
  • 11
  • 30