簡體   English   中英

如何持久保存JPA Map @OneToMany

[英]How to persist JPA Map @OneToMany

我有一個包含地圖的實體類。 該地圖引用了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。 映射鍵是我要保留的排名屬性。 我不希望rank屬性成為Child類的一部分。 我想實現一個連接表(parent_child),其中的列如下所示:

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

實際上,我沒有獲得等級列。 我想念什么? 這有可能嗎?

如上文所述,您將需要創建一個額外的實體,例如Relationship。 然后,您可以將其映射為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;
}

您不應該使用地圖,因為這個問題,您應該為您的parent_child創建一個實體,並創建@NamedQuery以返回帶有孩子的排名

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM