如何使用 JPA 注释引入多列约束?

我试图在 JPA 映射的实体上引入一个多键约束:

public class InventoryItem {
@Id
private Long id;


@Version
private Long version;


@ManyToOne
@JoinColumn("productId")
private Product product;


@Column(nullable=false);
private long serial;
}

基本上(产品,系列)对应该是独一无二的,但我只找到了一种方法来说,系列应该是独一无二的。这显然不是一个好主意,因为不同的产品可能有相同的序列号。

有没有一种方法可以通过 JPA 生成这个约束,或者我必须手动创建它到数据库?

87704 次浏览

You can declare unique constraints using the @Table(uniqueConstraints = ...) annotation in your entity class, i.e.

@Entity
@Table(uniqueConstraints={
@UniqueConstraint(columnNames = {"productId", "serial"})
})
public class InventoryItem {
...
}

Note that this does not magically create the unique constraint in the database, you still need a DDL for it to be created. But seems like you are using some sort of automated tool for creating the database based on JPA entity definitions.

As already answered, multi-column index can be added using @Table annotation. However, columnNames needs to be the name of actual DB columns, not the class attribute. So, if the column is like the following:

@Column(name="product_id")
Long productId;

Then the @Table annotation should be like the following

@Table(uniqueConstraints=
@UniqueConstraint(columnNames = {"product_id", "serial"}))