Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply unique constraints using annotation

@Column(name = "userId")
    @UniqueConstraint
    private Integer userId;

I am using these annotation for entering data into database table. i want to make userId field unique field. but when i am doing like it it is showing me error @UniqueConstraints is disallowed for this location.

like image 466
Romi Avatar asked Sep 21 '11 08:09

Romi


People also ask

Which of the following annotations can be used to specify unique Rdbms constraints in entity classes?

@UniqueConstraint Annotation. Annotation type UniqueConstraint specifies that a unique constraint is to be included in the generated DDL (Data Definition Language) for a table.

What is @entity annotation in spring?

The @Entity annotation specifies that the class is an entity and is mapped to a database table. The @Table annotation specifies the name of the database table to be used for mapping.

What is Uniqueconstraints?

The UNIQUE constraint ensures that all values in a column are different. Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint.

Which annotation is used to denote that more than one column behaves as a primary key?

A composite primary key, also called a composite key, is a combination of two or more columns to form a primary key for a table. In JPA, we have two options to define the composite keys: the @IdClass and @EmbeddedId annotations.


3 Answers

@Column(name = "userId",unique=true)

or if its an DB generated ID you can also do this

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
like image 122
NimChimpsky Avatar answered Oct 03 '22 23:10

NimChimpsky


Here's an example of how to use @UniqueConstraint:

@Entity
@Table(name = "contact", 
  uniqueConstraints = @UniqueConstraint(columnNames = {"name", "company_id"}))
public class Contact {
  ...
}

This specifies that the combination of the "name" column and the "company_id" column will be unique.

like image 27
MiguelMunoz Avatar answered Oct 03 '22 23:10

MiguelMunoz


And this is the explanation of the Hibernate doc version 3.5 for @UniqueConstraint definition.

 @Entity
    @Table(name="tbl_sky",uniqueConstraints = {@UniqueConstraint(columnNames={"month", "day"})})
    public class Sky implements Serializable {
       ...
    }

and this is for Hibernate 4.3 example for @UniqueConstraint

like image 6
erhun Avatar answered Oct 03 '22 23:10

erhun