我对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);
任何想法?
答案 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();