17
@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.

3 Answers 3

35
@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;
Sign up to request clarification or add additional context in comments.

2 Comments

It's not a primary key field.
@MiguelMunoz so neglect 2nd part of answer and go with first part i.e. @Column(name = "userId",unique=true)
23

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.

1 Comment

What is the package for the UniqueConstraint annotation?
6

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.