Jack
Jack

Reputation: 6640

How to force a field to avoid duplicates?

I have a class with two fields id and city, although I defined the city column as unique but it still accepts duplicates. How can I prevent duplicates?

@Id
@GeneratedValue
private long id;
@Column(name="City",unique=true)
private String City;

Upvotes: 1

Views: 91

Answers (1)

JamesENL
JamesENL

Reputation: 6540

The unique property (along with nullable, insertable and updatable) only has meaning if you are using Hibernate to generate out your database schema when you deploy. You have to modify your underlying database and add a unique constraint on that column. That way when you try to insert a duplicate record into that table, you will get a ConstraintViolationException

Upvotes: 4

Related Questions