【问题标题】:Specifying a bidirectional relationship in Hibernate between objects of the same class在 Hibernate 中指定同一类的对象之间的双向关系
【发布时间】:2013-08-30 16:30:17
【问题描述】:

我有一个 City 类,其中一些 City 对象将与其他 City 对象具有多对多关系。这种关系是姐妹城市关系,例如,城市对象东京可以与城市对象赫尔辛基和伦敦有姐妹城市关系,伦敦可以是东京、巴黎和明尼阿波利斯的姐妹城市。 我在这里阅读了文档:http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/,尤其是 2.2.5.3.2.1。多对多映射的定义部分。这是我的城市课:

@Entity
@Table(name = "city")
public class City {
@Id
@Column(name = "city_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private long cityID;

@Column(name = "name_txt")
private String cityName;

@OneToOne
@JoinColumn(name = "type_id")
private CityType cityType;

@OneToOne
@JoinColumn(name = "state_id")
private State state;

@Column(name = "population_nbr")
 private int population;

@Column(name = "area_nbr")
private double area;

  /** Mapping Entity Associations */ 

@ManyToMany(
    targetEntity=City.class,
    cascade = CascadeType.PERSIST, fetch = FetchType.EAGER
)
@JoinTable(name="sister_city",
        joinColumns = @JoinColumn(name="city_id"),
        inverseJoinColumns = @JoinColumn(name="sister_city_id")
)
    private List<City> sisterCities;

public City() {
cityType = new CityType();
state = new State();
}
    //Getters and Setters ....

我的关联表名为sister_city,它有三列,id、city_id 和sister_city_id。现在我可以创建一个新城市,在选择框中从先前创建的城市中选择姐妹城市,并将城市 ID 和所选姐妹城市 ID 添加到关联表的正确列中。

我的问题是当我添加新城市 Twig 并将其赋予东京、巴黎和伦敦的姐妹城市时,当我选择巴黎的姐妹城市时,Twig 没有与其他姐妹城市一起被选中。我已经阅读了 mappedBy 参数以及它如何指定多对多关系的所有者方属性,但是当对象来自同一个类时,你如何做到这一点?

现在,如果 Paris 有 city_id 18 和 Twig 24,则添加 city_id 18 --sister_city_id 24 关系,但也不会通过 Hibernate 自动添加 city_id 24 --sister_city_id 18 关系。

【问题讨论】:

    标签: hibernate many-to-many bidirectional


    【解决方案1】:

    我认为您遇到了必须单独更新每个双向关系的常见问题。这些关系不会自动发生。因此,您不仅需要将城市东京、巴黎和伦敦添加到 Twig,还必须执行相反的操作,对于您刚刚添加的每个城市,您必须建立相反的关系。换句话说,您必须将 Twig 添加到东京、巴黎和伦敦。请务必在为每个城市设置关系后调用更新。

    我认为 mappedBy 参数在这里没有意义。有关 mappedBy 参数的更多信息,请阅读以下内容:

    Can someone please explain mappedBy in hibernate?

    【讨论】:

      猜你喜欢
      • 2018-01-13
      • 2015-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 2018-10-28
      • 1970-01-01
      相关资源
      最近更新 更多