2011-09-08 61 views
2

我在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實體更新任何東西時,它不起作用。

我該怎麼辦?

回答

3

答案在於:協會的所有者一方是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); 
} 
+0

this.wheels.remove(w);和this.wheels.add(w);將不起作用,因爲您需要會話和事務上下文來調用這些方法 – george

相關問題