简体   繁体   English

在多个字段上设置唯一约束

[英]Putting unique constraint on multiple fields

Let's say I have an entity like this: 假设我有一个这样的实体:

@Entity
public Foo {
    @Id
    private Long id;

    private String name;

    private String type;

    ...
}

Is there a way to express that name and type should be unique together? 有没有办法表达名称和类型应该一起唯一? Meaning that for example you could have name "x" with type "y" and name "x" with type "z", but not an other "x" with type "y". 举例来说,这意味着您可以使用类型为“ y”的名称“ x”和类型为“ z”的名称“ x”,而不能使用类型为“ y”的其他名称“ x”。

@EmbeddedId doesn't do the trick since name can be changed later - type however remains the same throughout the lifecycle of the entity. @EmbeddedId不能解决问题,因为可以在以后更改名称-但是类型在实体的整个生命周期中都保持不变。

You can add Constraints for your Entity on the @Table annotation. 您可以在@Table批注上为您的实体添加约束。 In your case, you want to make two joined fields unique. 对于您的情况,您想使两个连接的字段唯一。 You would use the @UniqueConstraint annotation. 您将使用@UniqueConstraint批注。

@Entity
@Table(uniqueConstraints=
           @UniqueConstraint(columnNames = {"name", "type"}) 
public Foo {
    @Id
    private Long id;
    @Column
    private String name;
    @Column    
    private String type;

    ...
}

Take a look at the javadoc for @UniqueConstraint . 看看@UniqueConstraint的javadoc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM