hibernatespring-mvcjpahibernate-onetomanyhibernate-jpa

Hibernate @OneToMany Mapping fetching records


I have googled everywhere but unable to get what I need Unable to get the respective output. I have two classes Employee and EmployeeLocation and their respective tables in SQL.

This is my table For EmployeeLocation Table multiple emp_ids

Table

MyScenario -> In employee table id is the primary key and have unique values but in EmployeeLocation table I have that Employee id as emp_id in EmployeeLocation Table which is not unique which is appearing multiple time.

I am trying to achieve @OnetoMany Association but not succeeding. Help Appreciated.

class Employee {
     private integer id;
     @OneToMany(fetch=FetchType.EAGER,mappedBy="empId")
     private List<EmployeeLocation> employeeLocation;
     //getters and setters
}

 class EmployeeLocation {
      private integer id;
      private integer emp_id; 
      // emp_id is a primary key in employee table
      //fields  getters and setters 
}

Solution

  • In fact in the EmployeeLocation you need to have a reference to the mapped Employee and not the emp_id, because the mapping is based on the entity.

    So that's what you need :

    EmplyeeLocation:

    class EmployeeLocation {
    
          @Id
          private int id;
          @ManyToOne(cascade = CascadeType.ALL)
          private Employee emp; 
    }
    

    Employee:

    class Employee {
    
         @Id
         private int emp_id;
         @OneToMany(fetch=FetchType.EAGER, mappedBy="emp")
         @JoinColumn(name = "emp_id")
         private List<EmployeeLocation> employeeLocation;
    }
    

    Note: