我正在開發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數據庫工作正常一片空白。
請讓我知道我在做什麼錯,因爲地址表中的外鍵沒有被保存。
感謝, 卡邁勒
嗨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或服務。 –我更喜歡將它放在POJO中,因爲它保證Address員工字段將始終設置 - 以防萬一您將員工保存在其他地方。 – Kishan