我的实体包含如下所示的集合:
@ElementCollection
Set<String> branches;
现在Hibernate所做的是创建一个表project_branches
(project_id | branches)并在branches
上添加一个唯一约束。有没有办法告诉hibernate唯一约束应该同时涉及project_id
和 branches
?
我找不到这个问题的答案,虽然我觉得我不是第一个遇到这个问题的人......谢谢
答案 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>();