我有Worker和Department物體。Department包含一個串列Worker并Worker包含一個Department物體。所以這是一對多的關系。
工人
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Worker {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "worker_sequence")
@SequenceGenerator(name = "worker_sequence", sequenceName = "worker_sequence", allocationSize = 1)
private Long workerId;
private String name;
private String lastName;
private String email;
private LocalDate birth;
@ManyToOne()
@JoinColumn(name = "department_id")
private Department department;
}
部門
@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "department_sequence")
@SequenceGenerator(name = "department_sequence", sequenceName = "department_sequence", allocationSize = 1)
private Long departmentId;
private String name;
@OneToMany(mappedBy = "department", cascade = CascadeType.ALL)
private List<Worker> workers = new ArrayList<>();
public void addWorker(Worker worker) {
workers.add(worker);
}
}
控制器
@RestController
@RequestMapping("api")
public class DepartmentWorkerController {
DepartmentService departmentService;
WorkerService workerService;
@Autowired
public DepartmentWorkerController(DepartmentService departmentService, WorkerService workerService) {
this.departmentService = departmentService;
this.workerService = workerService;
}
@PutMapping("department/{departmentId}/worker/{workerId}")
public Department assignWorkerToDepartment(@PathVariable("departmentId") Long departmentId, @PathVariable("workerId") Long workerId) {
Department department = departmentService.getDepartmentById(departmentId);
Worker worker = workerService.getWorkerByID(workerId);
department.addWorker(worker);
return departmentService.saveDepartment(department);
}
}
問題是沒有錯誤但關聯沒有保存。除錯時,一切似乎都很好。
uj5u.com熱心網友回復:
查看 biderrection 關系在休眠中的作業方式。當您宣告 List 并將關系映射到 Department 時,不要創建另一個表并使用在 worker 表中創建的部門 ID 作為關系的目標。當您將 Worker 添加到 Department 類的 List 時在這種情況下,您的 Worker 部門為空,因為您說休眠在您的 Worker 表中使用 Department_id 作為關系所有者休眠沒有意識到這種關系。要解決您的問題,您需要將部門設定為 worker 作為 worker.setDepartment(department) ,然后將該作業人員添加到部門串列并保存部門,之后該作業人員將由級聯保存,并且部門 ID 將由您設定需要單獨保存
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/435812.html
上一篇:動態分配物件和intc
