@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.
@UniqueConstraint Annotation. Annotation type UniqueConstraint specifies that a unique constraint is to be included in the generated DDL (Data Definition Language) for a table.
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.
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.
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.
@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;
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With