gpt4 book ai didi

hibernate - 在双向多对一关系中从非所有者侧更新实体

转载 作者:行者123 更新时间:2023-12-04 06:15:06 27 4
gpt4 key购买 nike

我在 Spring Roo 中定义了两个实体之间的双向多对一关系。

@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;

}

所有者端(车轮)上的更改被保留。

当我尝试从 Car-entity 更新任何内容时,它不起作用。

我该怎么办?

最佳答案

答案就在问题中:关联的拥有者端是Wheel,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);
}

关于hibernate - 在双向多对一关系中从非所有者侧更新实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7348338/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com