1

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;
JamesENL
  • 6,400
  • 6
  • 39
  • 64
Jack
  • 6,430
  • 27
  • 80
  • 151
  • Check this, http://stackoverflow.com/questions/4546131/using-unique-constraint-on-hibernate-jpa2 This will create unique constraint on database when you export schema – Vinit Prajapati Jun 25 '14 at 06:14

1 Answers1

4

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

JamesENL
  • 6,400
  • 6
  • 39
  • 64
  • Shameless self-plug: Have a look at the [Hibernate Q&A](http://stackoverflow.com/questions/24257449/how-do-i-use-annotations-to-define-x-relationship-in-hibernate-4-and-spring) that I wrote to help new users get accustomed to Hibernate – JamesENL Jun 25 '14 at 06:16