Hibernate 注释中的@UniqueConstraint 和@Column (only = true)

@ UniqueConstraint@ 专栏(惟一 = 真实)有什么不同?

例如:

@Table(
name = "product_serial_group_mask",
uniqueConstraints = {@UniqueConstraint(columnNames = {"mask", "group"})}
)

还有

@Column(unique = true)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private ProductSerialMask mask;


@Column(unique = true)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private Group group;
175783 次浏览

来自 JavaEE 文档:

public abstract boolean unique

(可选)属性是否为唯一键。这是 表级别的 UniqueConstraint 注释,并且对于当唯一键 约束只是单个字段。此约束应用于任何约束之外 entailed by primary key mapping and to constraints specified at the table level.

参见 doc

除了波阿斯的回答..。

@UniqueConstraint允许您使用 命名约束,而 @Column(unique = true)则生成一个随机名称(例如 UK_3u5h7y36qqa13y3mauc5xxayq)。

有时了解一个约束与哪个表关联是有帮助的。例如:

@Table(
name = "product_serial_group_mask",
uniqueConstraints = {
@UniqueConstraint(
columnNames = {"mask", "group"},
name="uk_product_serial_group_mask"
)
}
)

如前所述,当 @Column(unique = true)只是一个字段时,它是到 UniqueConstraint的一个快捷方式。

From the example you gave, there is a huge difference between both.

@Column(unique = true)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private ProductSerialMask mask;


@Column(unique = true)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private Group group;

This code implies that both mask and group have to be unique, but separately. That means that if, for example, you have a record with a Id = 1 and tries to insert another record with Id = 1, you'll get an error, because that column should have unique values. The same aplies for group.

On the other hand,

@Table(
name = "product_serial_group_mask",
uniqueConstraints = {@UniqueConstraint(columnNames = {"mask", "group"})}
)

意味着掩码 + 组合的值应该是唯一的。这意味着,例如,您可以拥有一条带有 Id = 1Group. id = 1的记录,如果您尝试用 Id = 1Group. id = 2插入另一条记录,那么它将被成功插入,而在第一种情况下则不会。

如果你想让掩码和分组在类级别上都是唯一的,那么你必须编写如下代码:

@Table(
name = "product_serial_group_mask",
uniqueConstraints = {
@UniqueConstraint(columnNames = "mask"),
@UniqueConstraint(columnNames = "group")
}
)

这与第一个代码块具有相同的效果。

除了@Boaz 和@vegemite4me 的回答... ..。

By implementing ImplicitNamingStrategy you may create rules for automatically naming the constraints. Note you add your naming strategy to the metadataBuilder during Hibernate's initialization:

metadataBuilder.applyImplicitNamingStrategy(new MyImplicitNamingStrategy());

它适用于 @UniqueConstraint,但不适用于 @Column(unique = true),因为 @Column(unique = true)总是生成一个随机名称(例如 UK _ 3u5h7y36qqa13y3mauc5xxayq)。

有一个错误报告来解决这个问题,所以 如果可以的话,请投票支持。在这里: Https://hibernate.atlassian.net/browse/hhh-11586

谢谢。