views:

24

answers:

1
+2  Q: 

Transitive save

I have a question about hibernate.

I want to save a small graph of detached objects :

session.save(new City(1));

Peron p = new Person(new City(1), new Street(2));
session.save(p);

Hibernate told me that city is transient but I do :

session.refresh(city);
session.refresh(street);
session.update(p);

Any Idea?

+3  A: 

Either do something like this:

City city = new City(1);
session.save(city);

Street street = new Street(2);
session.save(street);

Peron p = new Person(city, street);
session.save(p);

session.flush();

Or setup cascading to cascade the save operation. For example, with annotations:

@Entity
public class Person {
    @Id @GeneratedValue
    private Long id;

    @ManyToOne(cascade = CascadeType.PERSIST) // or ALL to cascade all operations
    private City city;

    // ...
}

And then the code becomes:

City city = new City(1);
Street street = new Street(2);
Person p = new Person(city, street);
session.save(p);
session.flush();

References

  • JPA 1.0 specification
    • Section 3.2.1 "Persisting an Entity Instance"
    • Section 9.1.22 "ManyToOne Annotation"
  • Hibernate Core Reference Guide
  • Hibernate Annotations Reference Guide
Pascal Thivent
Thanks for your response, you know if we delete a Person, the delete will be cascaded no ?
Simo
@Simo If you configure Hibernate to cascade the delete operation too, yes it will.
Pascal Thivent