本文介绍了如何指定列的组合应该是使用注解的唯一约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保我的表中的所有行有两个领域的独特组合,我想在我的实体类指定这个使用注释。我一直在使用@Table和@UniqueConstraint但组合尝试显然我做错了,因为我只能似乎来指定单独的列应该是唯一的(我已经可以指定使用@列的唯一属性),而比列的组合。例如,我想其中有场A和B只包含具有A和B都不领域的一个独特的组合行的表/列的需要是唯一的,这是两者的结合应该是独一无二的。

I want to make sure that all rows in my table have a unique combination of two fields, and I want to specify this using annotations in my entity class. I have tried using a combination of @Table and @UniqueConstraint but apparently I'm doing it wrong, in that I can only seem to specify that the separate columns should be unique (I can already specify that using the @Column's unique property) rather than a combination of columns. For example I want a table which has fields A and B to contain only rows which have a unique combination of A and B. Neither field/column needs to be unique, it's the combination of the two which should be unique.

下面就是我没有快乐到目前为止已经试过:

Here's what I've tried so far with no joy:

@Table(name = "MY_TABLE", 
       uniqueConstraints = @UniqueConstraint(columnNames = 
                                             { "FIELD_A", "FIELD_B" }))

@Table(name = "MY_TABLE", 
       uniqueConstraints = { @UniqueConstraint(columnNames = 
                                               { "FIELD_A", "FIELD_B" }) })

有人可以请建议这样做的正确方法?此外,如果有可能使用JPA注释,而不是Hibernate的相关注解会是preferable。

Can someone please suggest the right way to do this? Also if it's possible to use JPA annotations instead of Hibernate-specific annotations that'd be preferable.

在此先感谢您的帮助。

- 詹姆斯

推荐答案

你的第二个尝试

@Table(name = "MY_TABLE", 
   uniqueConstraints = { @UniqueConstraint(columnNames = 
                                           { "FIELD_A", "FIELD_B" }) })

应该工作正常。

这篇关于如何指定列的组合应该是使用注解的唯一约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 06:42