Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a cascade save in hibernate

I have objects A and B.

Object A is like

class A{
 Set<B>
}

Now when I save A I want that all objects in Set<B> of A should be automatically saved in DB. How can I do it?

like image 468
akshay Avatar asked Jul 20 '11 13:07

akshay


2 Answers

// Use the cascade option in your annotation
@OneToMany(cascade = {CascadeType.ALL}, orphanRemoval = true)
public List<FieldEntity> getB() {
    return fields;
}
like image 72
Ransom Briggs Avatar answered Sep 27 '22 17:09

Ransom Briggs


The question from Ransom will work if you are working through EntityManager and using pure JPA annotations. But if you are using Hibernate directly, then you need to use its own annotation for cascading.

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

...

@OneToMany
@Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
public List<FieldEntity> getB() {
    return fields;
}
like image 44
Nikola Avatar answered Sep 27 '22 19:09

Nikola