[英]Why Foreign key not inserted in hibernate
我有兩個實體。 員工和地址。 這些實體之間的關系是@OneToOne。 當我想插入數據庫的外鍵不插入表。 我的實體是:
@Entity
@Table(name="Address")
public class Address{
@Id
@Column(name="Id")
private int Id;
@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name="emp_id",
insertable=true, updatable=false,
nullable=true)
private Employee employee ;
和員工實體
@Entity
@Table(name="EMPLOYEE")
public class Employee{
@Id
@GeneratedValue
@Column(name="emp_id")
private int emp_id;
@OneToOne(fetch =FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name="emp_id",
insertable=true, updatable=false,
nullable=true)
private Address address;
和添加員工的代碼
Employee employee = new Employee("john" , ... );
Address address = new Address("USA" , ...);
employee.setAddress(address);
address.setEmployee(employee);
employeeService.addEmployee(employee);
是否應該在數據庫表中指定外鍵?
您只需要關系擁有方的@JoinColumn
。 因此,如果在數據庫中有從Address
表的第emp_id
列到Employee
表的第id
列的外鍵,則映射應如下所示
地址
@Entity
@Table(name="Address")
public class Address {
...
@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name="emp_id",
insertable=true, updatable=false,
nullable=true)
private Employee employee ;
雇員
@Entity
@Table(name="EMPLOYEE")
public class Employee{
...
@OneToOne(fetch =FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "employee")
private Address address;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.