2011-09-08 64 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