gpt4 book ai didi

java - Hibernate中embedded member对成员的唯一约束

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:59:58 24 4
gpt4 key购买 nike

是否可以在 Hibernate 中为嵌入式类的成员定义唯一约束?

我需要确保 Nested::i1 和 Nested::i2 作为一对(组合)是唯一的

@Entity
@Table( uniqueConstrains = ???)
public class Widget {
@Id
private int id;

@Embedded
Nested nested;
}

@Embeddable
public class Nested {
private int i1;
private int i2;
}

最佳答案

可以通过使用:

@Entity
@Table(uniqueConstraints = { @UniqueConstraint(columnNames = {"i1", "i2"})})
public class Widget {

这将导致 CREATE SQL(postgresql 示例)

create table Widget 
( id int8 not null,
i1 int8,
i2 int8 ,
primary key (id),
unique (i1, i2)
)

可选 - 当您在一个文件中添加 @AttributeOverride 注释指定时,它可能会更简洁和可读 - 两个属性的列名

@AttributeOverrides({
@AttributeOverride(name = "i1", column = @Column(name = "i1")),
@AttributeOverride(name = "i2", column = @Column(name = "i2"))
})
@Embedded
Nested nested;

关于java - Hibernate中embedded member对成员的唯一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24661243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com