53

I am using SEAM 2/Hibernate along with PostgreSQL 9 database. I have the following table

Active Band
===========
active_band_id serial
active_band_user text
active_band_date timestamp
active_band_process integer

I would like to add a constraint that ensures each new entry has a unique combination of active_band_user and active_band_date.

There could potentially be many attempted inserts per second so I need this to be as efficient as possible, is there a SEAM / hibernate annotation I can use in the entity mapping?

Thanks in advance

DaveB
  • 2,953
  • 7
  • 38
  • 60
  • This appears to duplicate http://stackoverflow.com/questions/3211972/specifying-restrictions-unique-together-in-hibernate – Sarah Messer Apr 19 '17 at 14:52

3 Answers3

104

There is no Hibernate annotation that checks uniqueness before insert/update. But there is annotation which will generate such a constraint to database if automatic database creation is used:

 @Table(
    name="ACTIVE_BAND", 
    uniqueConstraints=
        @UniqueConstraint(columnNames={"active_band_user", "active_band_date"})
)
Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135
  • I dont think it supports this as I get 'The value for annotation attribute Table.uniqueConstraints must be some @javax.persistence.UniqueConstraint annotation' in Eclipse. Does this method generate the constraint in the SQL schema? – DaveB Aug 14 '12 at 17:24
  • 1
    Yes it does support. It is documented here: http://docs.oracle.com/javaee/6/api/javax/persistence/Table.html#uniqueConstraints%28%29 Something else must be wrong. Is javax.persistence.UniqueConstraint imported? – Mikko Maunu Aug 20 '12 at 10:56
  • 23
    I know this was years ago, but make sure you're using the `javax.persistence.Table` not `org.hibernate.annotations.Table`. Hibernate's `@Table` does not have a `uniqueConstraints` field. – Patrick Feb 05 '14 at 18:21
2

In a more modern syntax, it would be :

@Table(
    name="ACTIVE_BAND", 
    uniqueConstraints =
        [UniqueConstraint(
                columnNames = ["active_band_user", "active_band_date"]
        )]
)
NJellab
  • 21
  • 1
0

This syntax worked for me with Java 17

@Entity
@Table(name = "ELECTION_RESULTS",
    uniqueConstraints = { @UniqueConstraint(name = "UC_CP", columnNames = { "constituency", "party_code" }) })
  
public class ElectionResults {
 @Column(..)
 ......
}
ddc
  • 885
  • 6
  • 12