OneToMany映射无法在Spring Boot + Hibernate中运行

时间:2017-04-25 17:26:02

标签: spring-boot hibernate-mapping

我正在开发Spring Boot + Hibernate应用程序。我想知道如何保存OneToMany关系,包括外键。

我有2个类Employee和Address,它们具有OneToMany关系。

@Entity
public class Employee {

    @Id
    @GeneratedValue
    private int empId;
    private String name;
    private String designation;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "employee",fetch=FetchType.EAGER)
    private List<Address> addresses = new ArrayList<>();

    public List<Address> getAddresses() {
        return addresses;
    }

    public void setAddresses(List<Address> addresses) {
        this.addresses = addresses;
    }
}


@Entity
public class Address {

    @Id
    @GeneratedValue
    private int addressID;
    private String city;
    private String country;

    @ManyToOne(cascade = CascadeType.ALL,fetch=FetchType.LAZY)
    @JoinColumn(name = "empId")
    private Employee employee;

    public Employee getEmployee() {
        return employee;
    }

    public void setEmployee(Employee employee) {
        this.employee = employee;
    }
}

Dao Code:

@Repository
public class EmployeeDao {

    @Autowired
    private SessionFactory sessionFactory;

    public Employee save(Employee employee) {
        Session session = getSession();
        session.persist(employee);      
        return employee;

    }

    private Session getSession() {
        return sessionFactory.getCurrentSession();
    }
}

当我尝试使用json Post请求保存数据时:

{
  "name": "Kamal Verma",
  "designation": "SAL1",
  "addresses": [
    {
      "city": "Noida",
      "country": "India"
    }
  ]
}

它的工作正常,没有任何错误,但在地址表EMPID中的数据库中为空。

请告诉我,由于地址表中的外键没有被保存,我做错了什么。

谢谢, 哈拉

2 个答案:

答案 0 :(得分:0)

您必须设置&#39;员工&#39;您的地址类中的字段。

将Employee类中的setter更新为:

public void setAddresses(List<Address> addresses) {
    this.addresses.clear();

    for (Address address: addresses) {
      address.setEmployee(this);
      this.addresses.add(address);
    }
}

答案 1 :(得分:0)

在保存Employee对象之前,所有地址对象都必须设置雇佣参考,以便hibernate可以在地址故事中填充empId。

@Autowired
private SessionFactory sessionFactory;

public Employee save(Employee employee) {
    Session session = getSession();
    for(Address address: employee.getAddresses()){
        address.setEmployee(employee); //Set employee to address.
    }
    session.persist(employee);      
    return employee;

}

private Session getSession() {
    return sessionFactory.getCurrentSession();
}