Java 如何使用 Hibernate 获取两个字段的唯一键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/946512/
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-11 21:24:42  来源:igfitidea点击:

How to get a unique key for two fields with Hibernate?

javahibernateormjpaannotations

提问by James Adams

I have two fields of an entity class which I don't want to be unique but to instead be used as composite fields for a key which must itself be unique. For example I have two fields (name and version) which can be the same for other records but together they must be unique. What is the best way to do that using Hibernate (with annotations)? I am using Hibernate Validator for other fields but I am not sure of a way to use that to validate that two fields together compose a unique key. I am using a generic entity class which has an id generic type which can be swapped out for a composite key class but I have yet to get that to work very well.

我有一个实体类的两个字段,我不希望它们是唯一的,而是用作键的复合字段,该键本身必须是唯一的。例如,我有两个字段(名称和版本),它们对于其他记录可以相同,但它们一起必须是唯一的。使用 Hibernate(带注释)做到这一点的最佳方法是什么?我正在将 Hibernate Validator 用于其他字段,但我不确定如何使用它来验证两个字段一起构成一个唯一键。我正在使用一个通用实体类,它有一个 id 通用类型,可以换成复合键类,但我还没有让它工作得很好。

采纳答案by mtpettyp

This will create a unique key on the database:

这将在数​​据库上创建一个唯一的键:

@Table( name = "MYTABLE",
        uniqueConstraints = { @UniqueConstraint( columnNames = { "NAME", "VERSION" } ) } )

This will be enforced by the database on a update or persist.

这将由数据库在更新或持久化时强制执行。

You'd need to write your own custom validator if you wanted to enforce this using Hibernate Validator.

如果您想使用 Hibernate Validator 强制执行此操作,则需要编写自己的自定义验证器。

回答by Gray

We usually will wrap the two fields in an inner key class which is marked as @Embeddable. For example:

我们通常会将这两个字段包装在一个标记为@Embeddable 的内部键类中。例如:

@Entity
public class Foo {

  @EmbeddedId()
  private Key key;
  ...

  @Embeddable
  public static class Key {
    @Column(nullable=false)
    private String name;
    @Column(nullable=false)
    private int version;

    protected Key () {
      // for hibernate
    }
    public Key (String name, int version) {
      this.name = name;
      this.version = version;
    }
    ...
    // You probably want .equals and .hashcode methods
  }
}