开发者

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?开发者_StackOverflow社区


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
    • 10.11. Transitive persistence
  • Hibernate Annotations Reference Guide
    • 2.4.7. Cascade (extensions of the JPA specification)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜