简体   繁体   English

@UniqueConstraint超过两列

[英]@UniqueConstraint for more than two columns

In my Spring/hibernate project I'm using uniqueConstraints = {@UniqueConstraint(columnNames={"ID_A", "ID_B"})} to validate a unique combination of columns in a table. 在我的Spring / hibernate项目中,我使用uniqueConstraints = {@UniqueConstraint(columnNames={"ID_A", "ID_B"})}来验证表中列的唯一组合。 This works fine when I only have two columns. 当我只有两列时,这很好用。

However when I want to add a third column ID_C to the constraint it no longer works. 但是,当我想在约束中添加第三列ID_C时,它不再起作用。

  1. Does @UniqueConstraint only allow for two columns? @UniqueConstraint只允许两列吗?
  2. If yes, then how would I validate the unique combination for more than two columns? 如果是,那么我如何验证两列以上的唯一组合?

Thank you for the help, /D 谢谢你的帮助,/ D.

Edit: What I mean by "it no longer works" is that no exception is thrown when I add a new entry to the table. 编辑:我的意思是“它不再有效”是当我向表中添加新条目时不会抛出异常。 With two columns it throws an ConstraintViolationException . 有两列会抛出ConstraintViolationException

Adding UniqueConstraint alone to entity does not perform any validation. 仅将UniqueConstraint添加到实体不会执行任何验证。 As said in the linked documentation, it gives instructions that are used in database schema generation: 如链接文档中所述,它提供了在数据库模式生成中使用的指令:

Specifies that a unique constraint is to be included in the generated DDL for a primary or secondary table. 指定将唯一约束包含在主表或辅助表的生成DDL中。

Now you have two options left: 现在你还有两个选择:

  1. Let Hibernate to generate database schema 让Hibernate生成数据库模式
  2. Drop old constraint and add new by using SQL as usually. 删除旧约束并通常使用SQL添加新约束。

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

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