传递保存

时间:2010-10-09 06:16:21

标签: java hibernate orm

我对hibernate有疑问。

我想保存一个分离对象的小图:

session.save(new City(1));

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

Hibernate告诉我,这个城市很短暂,但我确实:

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

任何想法?

1 个答案:

答案 0 :(得分:3)

要么做这样的事情:

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();

或设置级联以级联save操作。例如,使用注释:

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

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

    // ...
}

然后代码变为:

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

参考

  • JPA 1.0规范
    • 第3.2.1节“坚持实体实例”
    • 第9.1.22节“ManyToOne注释”
  • Hibernate核心参考指南
  • Hibernate Annotations参考指南