@UniqueConstraint annotation in Java

JavaJpaUnique Constraint

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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):

Solution 2 - Java

You can use at class level with following syntax

@Entity
@Table(uniqueConstraints={@UniqueConstraint(columnNames={"username"})})
public class SomeEntity {
    @Column(name = "username")
    public String username;
}

Solution 3 - Java

I'm currently using play framework too with hibernate and JPA 2.0 annotation and this model works without problems

@Entity
@Table(uniqueConstraints={@UniqueConstraint(columnNames = {"id_1" , "id_2"})})
public class class_name {

@Id
@GeneratedValue
public Long id;

@NotNull
public Long id_1;

@NotNull
public Long id_2;

}

Hope it helped.

Solution 4 - Java

Note: In Kotlin the syntax for declaring the arrays in annotations uses arrayOf(...) instead of {...}

@Entity
@Table(uniqueConstraints=arrayOf(UniqueConstraint(columnNames=arrayOf("book", "chapter_number"))))
class Chapter(@ManyToOne var book:Book,
              @Column var chapterNumber:Int)

Note: As of Kotlin 1.2 its is possible to use the [...] syntax so the code become much simpler

@Entity
@Table(uniqueConstraints=[UniqueConstraint(columnNames=["book", "chapter_number"])])
class Chapter(@ManyToOne var book:Book,
              @Column var chapterNumber:Int)

Solution 5 - Java

Way1 :

@Entity
@Table(name = "table_name", 
       uniqueConstraints={
                          @UniqueConstraint(columnNames = "column1"),
                          @UniqueConstraint(columnNames = "column2")
                         }
      )

-> Here both Column1 and Column2 acts as unique constraints separately. Ex : if any time either the value of column1 or column2 value matches then you will get UNIQUE_CONSTRAINT Error.

Way2 :

@Entity
@Table(name = "table_name", 
       uniqueConstraints={@UniqueConstraint(columnNames ={"column1","column2"})})

-> Here both column1 and column2 combined values acts as unique constraints

Solution 6 - Java

   @Entity @Table(name = "stock", catalog = "mkyongdb",
   uniqueConstraints = @UniqueConstraint(columnNames =
   "STOCK_NAME"),@UniqueConstraint(columnNames = "STOCK_CODE") }) public
   class Stock implements java.io.Serializable {
   
   }

Unique constraints used only for creating composite key ,which will be unique.It will represent the table as primary key combined as unique.

Solution 7 - Java

@UniqueConstraint this annotation is used for annotating single or multiple unique keys at the table level separated by comma, which is why you get an error. it will only work if you let JPA create your tables

Example

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Builder(builderClassName = "Builder", toBuilder = true)
@Entity
@Table(name = "users", uniqueConstraints = @UniqueConstraint(columnNames = {"person_id", "company_id"}))
public class AppUser extends BaseEntity {

    @Column(name = "person_id")
    private Long personId;

    @ManyToOne
    @JoinColumn(name = "company_id")
    private Company company;
}

https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/UniqueConstraint.html

On the other hand To ensure a field value is unique you can write

@Column(unique=true)
String username;

Solution 8 - Java

Defining the Column Constraints

Whenever the unique constraint is based only on one field, we can use @Column(unique=true) on that column.

Let's define a unique constraint on the personNumber field:

@Column(unique=true)
private Long personNumber;

When we execute the schema creation process, we can validate it from the logs:

[main] DEBUG org.hibernate.SQL -
    alter table Person add constraint UK_d44q5lfa9xx370jv2k7tsgsqt unique (personNumber)
Defining Unique Constraints

JPA helps us to achieve that with the @UniqueConstraint annotation. We do that in the @Table annotation under the uniqueConstraints attribute. Let's remember to specify the names of the columns:

@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "personNumber", "isActive" }) })

We can validate it once the schema is generated:

[main] DEBUG org.hibernate.SQL -
    alter table Person add constraint UK5e0bv5arhh7jjhsls27bmqp4a unique (personNumber, isActive)

Solution 9 - Java

you can use @UniqueConstraint on class level, for combined primary key in a table. for example:

 @Entity
 @Table(name = "PRODUCT_ATTRIBUTE", uniqueConstraints = {
	   @UniqueConstraint(columnNames = {"PRODUCT_ID"}) })

public class ProductAttribute{}

Solution 10 - Java

Unique annotation should be placed right above the attribute declaration. UniqueContraints go into the @Table annotation above the data class declaration. See below:

@Entity
@Table(uniqueConstraints= arrayOf(UniqueConstraint(columnNames = arrayOf("col_1", "col_2"))))
data class Action(
        @Id @GeneratedValue @Column(unique = true)
        val id: Long?,
        val col_1: Long?,
        val col_2: Long?,
)

Solution 11 - Java

The value of the length property must be greater than or equal to name atribute length, else throwing an error.

Works

@Column(name = "typ e", length = 4, unique = true)
private String type;

Not works, type.length: 4 != length property: 3

@Column(name = "type", length = 3, unique = true)
private String type;

Solution 12 - Java

For me adding @Column(name = "column_name", length = 11, unique = true) worked

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionxyzView Question on Stackoverflow
Solution 1 - JavamdmaView Answer on Stackoverflow
Solution 2 - JavaDivanshuView Answer on Stackoverflow
Solution 3 - JavaFrancescoMView Answer on Stackoverflow
Solution 4 - JavaGlenPetersonView Answer on Stackoverflow
Solution 5 - JavaManjunath H MView Answer on Stackoverflow
Solution 6 - JavaCodamRanjanView Answer on Stackoverflow
Solution 7 - JavaTanvirChowdhuryView Answer on Stackoverflow
Solution 8 - Javaoura2View Answer on Stackoverflow
Solution 9 - Javahashem yousefiView Answer on Stackoverflow
Solution 10 - JavaR LuView Answer on Stackoverflow
Solution 11 - JavaAngel Quiroz SorianoView Answer on Stackoverflow
Solution 12 - JavaPKSView Answer on Stackoverflow