我在hibernate中執行一對一(一個員工<-> one Mobile)關係,如下所示。這段代碼工作正常,但由於這是一對一的關係,因此將相同的手機號碼分配給emp1和emp2應該產生了問題(它違反了關係),但代碼正在接受並在同一移動設備上添加2個emp(從數據庫表中確認)。爲什麼冬眠一對一的關係就像一個手機< - >很多員工? 我的代碼: @Entity冬眠中的一對一關係
public class Employee {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
@OneToOne
private Mobile mobile;
//...rest of the code
}
@Entity
public class Mobile {
@Id @GeneratedValue
private int id;
private long number;
//...rest of the code
}
Test Client main(...){
Mobile mobile = new Mobile(9999999999L);
Employee emp1 = new Employee("Raja");
Employee emp2 = new Employee("Raja");
emp1.setMobile(mobile);
emp2.setMobile(mobile);// VIOLATING 1-1 RELATIONSHIP
//...REST OF THE COMMON CODE
session.save(mobile);
session.save(emp1);
session.save(emp2);
session.getTransaction().commit();
}
數據庫顯示,都與同一個移動號碼EMP記錄(1-1違例)
你使用hibernate屬性'hibernate.hbm2ddl.auto'來生成你的表嗎?當hibernate負責創建表時,它會自動添加唯一性約束,否則你必須手動添加它。 –
可能的重複https://stackoverflow.com/questions/8968294/why-onetoone-is-allowing-duplicate-associations –
是的,這與評論鏈接中的問題類似。道歉重複 –