假设我的应用程序中有一个Department和Employee实体,并且我希望能够保存一个Department,但是在保存操作中还要保存任何可能提供的雇员。
我正在使用Cascade.PERSIST,保存了Department和Employee实体,但是问题是Department_id(外键)没有自动保存在雇员实体中。
我知道我可以将每个员工的部门设置为服务层,但是我想知道是否还有其他方法(也许有一些注释或属性)来自动保存部门ID。
示例代码:
@Entity
@Table(name = "DEPARTMENTS")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String deptName;
@OneToMany(mappedBy = "department", cascade = { CascadeType.PERSIST, CascadeType.MERGE })
private Set<Employee> employees;
// getters and setters
}
@Entity
@Table(name = "EMPLOYEES")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String fullName;
private Double salary;
@ManyToOne
@JoinColumn
private Department department;
// getters and setters
}
@PostMapping("/")
public void save(@RequestBody Department department) {
//can the next line be avoided:
//department.getEmployees().stream().forEach(e -> e.setDepartment(department));
departmentRepository.save(department);
}
样品申请正文:
{
"deptName" : "Sales",
"employees" : [
{
"fullName" : "Test",
"salary" : 1200.00
}
]
}
答案 0 :(得分:0)
您可以启用hibernate show_sql属性,以检查执行保存操作时hibernate触发的查询。另外,您可以设置“ hibernate.hbm2ddl.auto”来创建以查看DDL语句。
IMO,您缺少JoinColumn名称和可为空的属性,它应该是这样的
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" id="field1">
<input type="text" id="field2">
<input type="text" id="field3">
<input type="text" id="field4">
<input type="button" value="Submit">
</form>