如何坚持JPA Map @OneToMany

时间:2014-10-24 22:07:45

标签: java jpa map one-to-many

我有一个包含地图的实体类。该地图引用了Child类型的排名实体。

@Entity
public class Parent implements Serializable {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Integer id;
  @OneToMany
  @JoinTable    
  private Map<String, Child> ranking;
}

@Entity
public class Child implements Serializable {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Integer id;
}

我将对象放入地图中,如下所示:

ranking.put(1, childA);
ranking.put(2, childB);
ranking.put(3, childA);

Child类不引用Parent。 map键是我想要保留的排名属性。我不希望排名属性成为Child类的一部分。 我想实现一个连接表(parent_child),其中列如下所示:

|-------------| |----------| |---------------|
| parent      | | child    | | parent_child  |
|-------------| |----------| |---------------|
| id          | | id       | | parent_id     |
| ...         | | ...      | | child_id      |
|             | |          | | ranking       | <-- missing
|-------------| |----------| |---------------|

实际上,我没有得到排名栏。 我错过了什么?这甚至可能吗?

2 个答案:

答案 0 :(得分:1)

如上所述,您需要创建一个额外的实体,比如关系。然后,您可以将其映射为Map,如:

@Entity
public class Parent implements Serializable {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Integer id;

  @OneToMany(mappedBy ="parent")
  @JoinColumn(name = "parent_id")
  @MapKeyColumn(name = "ranking")
  private Map<String, Relationship> ranking;
}

答案 1 :(得分:0)

你不应该在你的情况下使用map,对于这个问题,你应该为你的parent_child创建一个实体并创建@NamedQuery以返回有孩子的等级

相关问题