2017-04-25 97 views
0

我正在開發Spring Boot + Hibernate應用程序。我想知道如何保存OneToMany關係,包括外鍵。OneToMany映射不能在Spring Boot + Hibernate中工作

我有2類僱員和地址有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代碼:

@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數據庫工作正常一片空白。

請讓我知道我在做什麼錯,因爲地址表中的外鍵沒有被保存。

感謝, 卡邁勒

回答

0

你必須設置你的地址類中的「員工」字段。

更新二傳手在你的員工類:

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

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

嗨Kishan,非常感謝您的建議。有效。只是想知道後張貼這個問題,我也找到了解決方案,通過更改服務爲 公共職員保存(員工僱員){ \t \t設置

addresses = employee.getAddresses(); \t \t(Address address:addresses){ \t \t \t address.setEmployee(employee); \t \t} \t \t return dao.save(employee); \t}所以,想要檢查一下什麼應該是最好的做法,把它放在Pojo或服務。 –

+0

我更喜歡將它放在POJO中,因爲它保證Address員工字段將始終設置 - 以防萬一您將員工保存在其他地方。 – Kishan

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(); 
}