Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spring Data JPA not saving one-to-many mapping

I have Worker and Department entity. Department contains a list of Worker and Worker contains a Department entity. So it’s a one to many relationship.

Worker

    @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;
    
    }

Departmant

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Controller

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

The issue is there is no error but association not saving. When debugging, everything seems fine.

>Solution :

See how the biderection relationship works in hibernate.When you declared List and map the relationship to Department not to create another table and to use also created department_id in worker table as the target of the relationship.When you add Worker to List of Department class in that situation the Department of your Worker is null any as you say hibernate to use department_id in your Worker table as relationship owner
hibernate do not realize the relationship.
To solve your problem you either need to set the department to worker as worker.setDepartment(department) and after that add that worker to department list and save the department after that the worker will be saved by cascade and the department_id will be set either you need to save them seperately

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading