java - Incorrect order of records in M-M relationship in hibernate -


i have 4 records in bridge table in mysql database. using @manytomany in hibernate, accurate order of employees incorrect incorrect of projects. following required material figure out doing mistake.

original data in mysql database

but following result @ stdout

this source.

        @entity         @table(name="project")         public class projectbean {              @id @generatedvalue @column(name="project_id")             private int projectid;             @column(name="title")             private string projecttitle;             @manytomany(mappedby="projects")             private collection<employeebean> employees;             public projectbean() {                 employees = new arraylist<employeebean>();             }              //getters & setters }    @entity @table(name="employee") public class employeebean {     @id @generatedvalue @column(name="employee_id")     private int employee_id;     @column(name="first_name")     private string firstname;     @column(name="last_name")     private string lastname;     @manytomany     @jointable(name="employee_project",joincolumns=@joincolumn(name="employee_id"),inversejoincolumns=@joincolumn(name="project_id"))     private collection<projectbean> projects;      public employeebean() {          projects = new arraylist<projectbean>();     }     //getters , setters goes here } 

and following main class trying traverse list same order can see in top image.

        arraylist<projectbean> projects = (arraylist<projectbean>)session.createquery("select projects employeebean").list();         arraylist<employeebean> employees = (arraylist<employeebean>)session.createquery("select employees projectbean").list();         system.out.println("empid\tprjid");         int = 0;         (employeebean employeebean : employees) {             system.out.print(employeebean + "\t");             projectbean projectbean = (projectbean) projects.get(i);             i++;             system.out.println(projectbean);         } 

your code doesn't make sense. iterate through employees, , each employee @ index i in list of employees, you're printing project @ index i of list of projects.

if want display projects of each employee, need single query, , 2 nested loops:

list<employeebean> employees = session.createquery("select e employeebean e").list(); (employeebean employee : employees) {     system.out.println(employee);     (project project : employee.getprojects()) {         system.out.println("\t" + employee);     } } 

also, note don't cast list return query arraylist: useless, , works because hibernate happens return arraylist. choose return other list instance, , code break. program on interfaces.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -