2014-06-25 88 views
1

我有兩個字段ID和城市類,雖然我將城市列定義爲唯一的,但它仍然接受重複。我怎樣才能防止重複?如何強制字段以避免重複?

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

檢查此問題,http://stackoverflow.com/questions/4546131/using-unique-constraint-on-hibernate-jpa2 This將導出模式時會對數據庫創建唯一性約束 –

回答

4

unique特性(與nullableinsertableupdatable一起)纔有意義,如果你正在使用Hibernate在部署產生了數據庫架構。您必須修改您的基礎數據庫並在該列上添加唯一約束。這樣,當您嘗試將重複記錄插入該表格時,您將獲得一個ConstraintViolationException

+0

無恥自插:看看[Hibernate問答](http://stackoverflow.com/questions/24257449/how-do-i-use-annotations-to- Hibernate-4-and-spring中的define-x-relationship),這是我寫的,以幫助新用戶習慣Hibernate – JamesENL