JPA:如何建模Map <string,set <object =“”>&gt; (嵌套集合)</string,>

时间:2015-03-18 14:10:25

标签: java hibernate jpa collections nested

这个问题与此有关 Is it possible to map a map<String,List<Entity>> in JPA?但遗憾的是,评分最高的答案并没有太大帮助。

相关文章http://en.wikibooks.org/wiki/Java_Persistence/Relationships#Nested_Collections.2C_Maps_and_Matrices也捕获了不同的用例,因为主要实体与MapKey(ProjectType)相关。

在我的用例中,公司使用多个帐户。帐户应按使用类型(称为AccountType)分组。所以我在CompanyEntity中想要的基本上就像

@MapKeyColumn(name = "TYPE")
@MapKeyEnumerated(EnumType.STRING)
//Missing JPA-Magic
private Map<AccountType, Set<AccountEntity>> accounts;

我的数据模型: http://i.stack.imgur.com/MORgD.png

如何以最优雅的方式实现此映射?

非常感谢!

2 个答案:

答案 0 :(得分:1)

您可以创建一个包含AccountEntity集的对象,如:

public class Accounts{
  @Id
  @GeneratedValue
  private long id;

  @Column(name="ACC_TYPE")
  private String type;


  @ManyToMany
  private Set<AccountEntity> accounts;
}

然后拥有您的CompanyEntity:

@MapKeyColumn(name = "TYPE")
@MapKeyEnumerated(EnumType.STRING)
private Map<AccountType, Accounts accounts;

答案 1 :(得分:-1)

以下是如何在JPA中管理参考表的答案:

JPA reference table mapping