具有Hibernate </string>的Set <string>的唯一约束

时间:2012-10-29 13:59:09

标签: java hibernate

我的实体包含如下所示的集合:

@ElementCollection
Set<String> branches;

现在Hibernate所做的是创建一个表project_branches(project_id | branches)并在branches上添加一个唯一约束。有没有办法告诉hibernate唯一约束应该同时涉及project_id branches

我找不到这个问题的答案,虽然我觉得我不是第一个遇到这个问题的人......谢谢

2 个答案:

答案 0 :(得分:2)

这取决于映射中涉及的列。

还有另外一种配置。请考虑在实体级添加UniqueConstraint注释,例如下面:

  @Table(name="project_branches",
    uniqueConstraints = {@UniqueConstraint(columnNames={"project_id", "branches"})}
  )

编辑:尝试使用@CollectionTable注释。

 @ElementCollection
 @CollectionTable(
    name="project_branches",
    joinColumns=@JoinColumn(name="branches"),
    uniqueConstraints = {@UniqueConstraint(columnNames={"project_id", "branches"})}
  )
  Set<String> branches;

答案 1 :(得分:1)

好的,我找到了解决方案:实体字段支持注释@CollectionTable,所以我能够像这样解决它:

@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "project_branches", uniqueConstraints = @UniqueConstraint(columnNames = {
        "project_id", "branches" }))
Set<String> branches = new HashSet<String>();