为什么外键没有插入到休眠状态 [英] Why Foreign key not inserted in hibernate
本文介绍了为什么外键没有插入到休眠状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的实体是:
$ p $
@Entity
@Table(name =Address)
公共类地址{
@Id
@Column(name =Id)
private int Id;
$ b $ @ @OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name =emp_id,
insertable = true,updatable = false,
nullable = true)
私人雇员雇员;
和员工实体
@Entity
@Table(name =EMPLOYEE)
public class Employee {
@Id
@GeneratedValue
@ Column(name =emp_id)
private int emp_id;
$ b $ @ @OneToOne(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
@JoinColumn(name =emp_id,
insertable = true,updatable = false,
nullable = true)
私有地址;
和添加员工的代码
Employee employee = new Employee(john,...);
地址=新地址(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,可更新= false,
nullable = true)
私人员工雇员;
员工
@Entity
@Table(name =EMPLOYEE)
public class Employee {
...
@OneToOne(fetch = FetchType.EAGER,cascade = CascadeType.ALL,mappedBy =employee)
私有地址;
i have two entities. Employee and address. relation between this entities is @OneToOne. when i want to insert into db the foreign key not be insert into table. my entity are:
@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 ;
and employee entity
@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;
and code for add employee
Employee employee = new Employee("john" , ... );
Address address = new Address("USA" , ...);
employee.setAddress(address);
address.setEmployee(employee);
employeeService.addEmployee(employee);
Should foreign keys in database tables is specified ?
解决方案
You only need @JoinColumn
on the owning side of a relationship. So, if in database you have foreign key from Address
table, column emp_id
to Employee
table, column id
, the mapping should look like this
Address
@Entity
@Table(name="Address")
public class Address {
...
@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name="emp_id",
insertable=true, updatable=false,
nullable=true)
private Employee employee ;
Employee
@Entity
@Table(name="EMPLOYEE")
public class Employee{
...
@OneToOne(fetch =FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "employee")
private Address address;
这篇关于为什么外键没有插入到休眠状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文