Hibernate 在双向多对一关系中从非所有者端更新实体
我在SpringRoo中定义了两个实体之间的双向多对一关系Hibernate 在双向多对一关系中从非所有者端更新实体,hibernate,jpa,spring-roo,Hibernate,Jpa,Spring Roo,我在SpringRoo中定义了两个实体之间的双向多对一关系 @RooEntity public class Car { @OneToMany(mappedBy="car") private Set<Wheel> wheels = new HashSet<Wheel>(); } @RooEntity public class Wheel { @ManyToOne @JoinColumn (name = "wheels_fk") private C
@RooEntity
public class Car {
@OneToMany(mappedBy="car")
private Set<Wheel> wheels = new HashSet<Wheel>();
}
@RooEntity
public class Wheel {
@ManyToOne
@JoinColumn (name = "wheels_fk")
private Car car;
}
@rootentity
公车{
@OneToMany(mappedBy=“汽车”)
private Set wheels=new HashSet();
}
@RooEntity
公共级车轮{
@许多酮
@JoinColumn(name=“wheels\u fk”)
私家车;
}
所有者侧(控制盘)上的更改将保持不变
当我试图更新汽车实体中的任何内容时,它不起作用
对此我能做些什么?答案在问题中:关联的所有者端是轮子,Hibernate将只使用所有者端来决定关联是否存在。在更新非所有者侧时,应始终更新所有者侧(如果需要连贯的对象图,则反之亦然)。最可靠的方法是将其封装在Car实体中:
public void addWheel(Wheel w) {
this.wheels.add(w);
w.setCar(this);
}
public void removeWheel(Wheel w) {
this.wheels.remove(w);
w.setCar(null);
}
public Set<Wheel> getWheels() {
// to make sure the set isn't modified directly, bypassing the
// addWheel and removeWheel methods
return Collections.unmodifiableSet(wheels);
}
public void addWheel(车轮w){
本.车轮.添加(w);
w、 赛特卡尔(本);
}
公共无效移除轮(轮w){
此。车轮。拆卸(w);
w、 setCar(空);
}
公共设置getWheels(){
//要确保集合未被直接修改,请绕过
//addWheel和removeWheel方法
返回集合。不可修改集合(轮子);
}
此。车轮。拆卸(w);加上(w);无法工作,因为您需要会话和事务上下文来调用这些方法