在 Hibernate JPA2 上使用唯一约束

发布于 2024-10-09 21:31:35 字数 128 浏览 0 评论 0原文

如何在 hibernate POJO 上实现我的独特约束?假设数据库不包含任何内容。

我在 @Column() 注释中看到了唯一的属性,但我无法让它工作?
如果我想将此约束应用于多个列怎么办?

How can I implement my unique constraints on the hibernate POJO's? assuming the database doesn't contain any.

I have seen the unique attribute in @Column() annotation but I couldn't get it to work?
What if I want to apply this constraint to more than one column?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

°如果伤别离去 2024-10-16 21:31:35

您可以在类中使用 @Table(uniqueConstraints = ...) 注解声明唯一约束

@Entity
@Table(uniqueConstraints=
           @UniqueConstraint(columnNames = {"surname", "name"})) 
public class SomeEntity {
    ...
}

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

@Entity
@Table(uniqueConstraints=
           @UniqueConstraint(columnNames = {"surname", "name"})) 
public class SomeEntity {
    ...
}
゛时过境迁 2024-10-16 21:31:35

基本上,没有数据库支持就无法实现唯一约束。

@Column@UniqueConstraintunique 属性是模式生成工具生成相应约束的指令,它们本身不实现约束。

您可以在插入新实体之前进行某种手动检查,但在这种情况下,您应该意识到并发事务可能出现的问题。

因此在数据库中应用约束是首选。

Bascially, you cannot implement unique constraint without database support.

@UniqueConstraint and unique attribute of @Column are instructions for schema generation tool to generate the corresponsing constraints, they don't implement constraints itself.

You can do some kind of manual checking before inserting new entities, but in this case you should be aware of possible problems with concurrent transactions.

Therefore applying constraints in the database is the preferred choice.

猫卆 2024-10-16 21:31:35

在 JPA2 中,您可以将唯一约束直接添加到字段:

@Entity
@Table(name="PERSON_TABLE") 
public class Person{
  @Id
  @Column(name = "UUID")
  private String id;

  @Column(name = "SOCIALSECURITY", unique=true)
  private String socialSecurityNumber;

  @Column(name = "LOGINID", unique=true)
  private String loginId;
}

恕我直言,将唯一约束直接分配给属性比在表的开头分配要好得多。

但是,如果您需要声明一个复合唯一键,那么在 @table 注释中声明它是您唯一的选择。

In JPA2, you can add the Unique constraint directly to the field:

@Entity
@Table(name="PERSON_TABLE") 
public class Person{
  @Id
  @Column(name = "UUID")
  private String id;

  @Column(name = "SOCIALSECURITY", unique=true)
  private String socialSecurityNumber;

  @Column(name = "LOGINID", unique=true)
  private String loginId;
}

IMHO its much better to assign the unique constraint directly to the attributes than at the beggining of the table.

If you need to declare a composite unique key however, then declaring it in the @table annotation is your only option.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文