考虑如下类:
class Person {
@Column(name = "id")
Integer id;
@Column(name = "name")
String name;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "owner")
List <Car> cars;
}
class Car {
@Column(name = "name")
String name;
@Column(name = "plate")
String plate;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="id", nullable=false)
Person owner;
}
现在,当我们来保存一个人物时:
Transaction tx = session.beginTransaction();
session.save(person);
for (Car c : person.getCars()) {
session.save(c);
}
tx.commit();
是不是只能将Hibernate交给java对象并让它保存一切?
答案 0 :(得分:0)
谢谢aviad。这正是我所需要的。 为了将来参考,这里是我使用的代码...
class Person {
@Column(name = "id")
Integer id;
@Column(name = "name")
String name;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "owner", orphanRemoval=true)
@Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
List <Car> cars;
}
class Car {
@Column(name = "name")
String name;
@Column(name = "plate")
String plate;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="id", nullable=false)
Person owner;
}
唯一真正的区别是您必须确保在保存父级之前已完成对链接对象的任何更新。
即。这不起作用。
Transaction tx = session.beginTransaction();
session.save(person);
for (Car c : person.getCars()) {
c.setName(c.getName() + " Update test");
}
tx.commit();
但这会
Transaction tx = session.beginTransaction();
for (Car c : person.getCars()) {
c.setName(c.getName() + " Update test");
}
session.save(person);
tx.commit();