Skip to content
Advertisement

Unable to fetch Parent data from Child

I’m trying to see whether a Cab is assigned to any Employee so I can fetch that Employee Id and simply to set cab as null, but @OneToMany mapping, simply returning a list of Employees & by this I’m not getting any method like a cab.getEmp() to fetch employee details

Employee.java

@Data
@Entity
@Table(name = "employee")
public class Employee {
    
     @Id
     private Integer id;
     private String username;
     private String password;
     private String role;
     private String dropLocation;
    
     @ManyToOne(
         cascade = CascadeType.ALL,
         fetch = FetchType.EAGER
     )
    
     @JoinColumn(
         name = "empCab",
         referencedColumnName = "cabId"
     )

     public Cab cab;
}

Cab.java

@Data
@Entity
@Table(name = "cab")
public class Cab {
    
     @Id
     private Integer cabId;
     private Integer cabNumber;
     private String cabShift;
        
     @OneToMany(
         cascade = CascadeType.ALL,
         fetch = FetchType.EAGER,
         mappedBy= "cab"
     )

     private List<Employee> emp = new ArrayList<>();
}

Controller

@GetMapping("deleteCab")
public ModelAndView deleteCab(@RequestParam("id") Integer id, ModelAndView mvc){
         Cab cab = cabRepo.findById(id).orElse(null);
         if(cab!=null){
             List<Employee> emp =  cab.getEmp();
             if(!cab.getEmp().isEmpty()){
                 //e1.setCab(null);
                 //empRepo.save(e1);
                 mvc.addObject("msg", "Cab deleted & an employee cab detail also got changed");
                 mvc.setViewName(NOTHING_JSP);
             } else {
                 cabRepo.deleteById(id);
                 mvc.addObject("msg", "Cab removed from the database");
                 mvc.setViewName(NOTHING_JSP);
             }
         }
}

Advertisement

Answer

In your code, Cab is perent class and Employee is child class and your goal is to remove the child class dependency with parent class. For that, You have to extract the Employee from Cab and remove the relationship with Cab using employee.setCab(null).

@GetMapping("/deleteCab")
@ResponseBody
public ModelAndView deleteCab(@RequestParam("id") Integer id, ModelAndView mvc){
    Cab cab = cabRepo.findById(id).orElse(null);
    if(cab != null){
         // Extract employee from cab
         for(Employee emp: cab.getEmp())
         {
            // Remove the relationship with cab
            emp.setCab(null);
         }
         cabRepo.save(cab);
         mvc.addObject("msg", "Cab deleted & an employee cab detail also got changed");
         mvc.setViewName(NOTHING_JSP);
    } else {
         cabRepo.deleteById(id);
         mvc.addObject("msg", "Cab removed from the database");
         mvc.setViewName(NOTHING_JSP);
    }
    return mvc;
}
Advertisement