@UniqueConstraint annotation in Java

xyz picture xyz · Jun 27, 2010 · Viewed 241.9k times · Source

I have a Java bean. Now, I want to be sure that the field should be unique.

I am using the following code:

@UniqueConstraint(columnNames={"username"})
public String username;

But I'm getting some error:

@UniqueConstraint is dissallowed for this location

What's the proper way to use unique constraints?

Note: I am using play framework.

Answer

mdma picture mdma · Jun 27, 2010

To ensure a field value is unique you can write

@Column(unique=true)
String username;

The @UniqueConstraint annotation is for annotating multiple unique keys at the table level, which is why you get an error when applying it to a field.

References (JPA TopLink):