java - JPA one to many relationship query -


implemented 1 many relationship , working fine.

my issue when run below query, if table has 100 employee rows, , each employee has 2 departments. database query called 101 times, because each employee calling department query, taking long complete calling hundred rows, can 1 suggest alternative solution?

please see details below

queries calling:

    first query :    select * employee e      next 100 queries : select * department d d.employeeid=? 

jpa database call :

    javax.persistence.query query = em.createnamedquery("select * employee e", employee.class);      return query.getresultlist();         import javax.persistence.cascadetype;     import javax.persistence.column;     import javax.persistence.entity;     import javax.persistence.fetchtype;     import javax.persistence.id;     import javax.persistence.namednativequeries;     import javax.persistence.namednativequery;     import javax.persistence.onetomany;     import javax.persistence.table;      @entity     @table(name = "employee")     public class employee implements serializable     {         @id         @column(name = "employeeid")         string employeeid;          @onetomany(mappedby = "employee", cascade = cascadetype.all, fetch = fetchtype.eager)         private list<department> departments;          public list<department> getdepartments() {             return departments;         }          public void setdepartments(list<department> departments) {             this.departments = departments;         }          public string getemployeeid() {             return employeeid;         }          public void setemployeeid(string employeeid) {             this.employeeid = employeeid;         }     }      @entity     @table(name = "department")     public class department implements serializable     {         private static final long serialversionuid = 1l;          @id         @column(name = "departmentid")         string departmentid;          @manytoone(fetch = fetchtype.eager)         @joincolumn(name = "employeeid", insertable = false, updatable = false)         private employee employee;     } 

the output xml:

        <employees>             <employee>                 <name>rob</name>                 <departments>                     <departmnet><id>1</id></departmnet>                     <departmnet><id>2</id></departmnet>                 </departments>               </employee>             <employee>                 <name>sam</name>                 <departments>                     <departmnet><id>1</id></departmnet>                     <departmnet><id>2</id></departmnet>                 </departments>               </employee>         </employees> 

this typical n+1 selects issue. solve join fetch queries described here , here


Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -