How to specify that a combination of columns should be a unique constraint using annotations?

核能气质少年 提交于 2019-12-06 19:10:43

问题


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" }))

and

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

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.

Thanks in advance for your help.

--James


回答1:


your second try

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

should work as expected.



来源:https://stackoverflow.com/questions/3504477/how-to-specify-that-a-combination-of-columns-should-be-a-unique-constraint-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!