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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2772470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:40:56  来源:igfitidea点击:

How to introduce multi-column constraint with JPA annotations?

javajpamapping

提问by plouh

I am trying to introduce a multi-key constraint on a JPA-mapped entity:

我正在尝试在 JPA 映射实体上引入多键约束:

public class InventoryItem {
    @Id
    private Long id;

    @Version 
    private Long version;

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

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

Basically (product, serial) pair should be unique, but I only found a way to say that serial should be unique. This obviously isn't a good idea since different products might have same serial numbers.

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

Is there a way to generate this constraint via JPA or am I forced to manually create it to DB?

有没有办法通过 JPA 生成这个约束,还是我被迫手动将它创建到数据库?

采纳答案by psp

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

您可以使用@Table(uniqueConstraints = ...)实体类中的注释声明唯一约束,即

@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.

请注意,这不会神奇地在数据库中创建唯一约束,您仍然需要一个 DDL 来创建它。但似乎您正在使用某种自动化工具来创建基于 JPA 实体定义的数据库。

回答by SJha

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

如前所述,可以使用@Table注释添加多列索引。但是,columnNames需要是实际数据库列的名称,而不是类属性。因此,如果该列如下所示:

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

Then the @Tableannotation should be like the following

那么@Table注解应该像下面这样

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