Search code examples
jpaeclipselinkjpa-2.0

ManyToOne doing multiple queries to fetch records


I have two entities, and dept_id is the foreign key here.

public class Student implements Serializable {
  ...
  @Id
  @Column(name="id")
  private Integer id; 

  @ManyToOne
  @JoinColumn(name = "dept_id")
  private Department department;
  ...
}

and

public class Department implements Serializable {
  ...
  @Id
  @Column(name="id")
  private Integer id; 

  @Column(name = "name")
  private String name;
  ...
}

Now I am doing the following JPQL where I have around 100 parameters inside in query:

select o from Student o where o.id in(1,2,7,9,15,16, ...)

When I see the JPA log, I found it is fetching 100 records from the Student by one query. After that it is doing 100 separate queries to fetch the Department for each Student. So far my understanding is the I/O operation should be slow. Is there any way so that it fetches everything by a single query?


Solution

  • I found this worked for me:

    query.setHint("eclipselink.join-fetch", "o.department");
    

    Also, I found this one is handy as it does not make any joining, but fetches the records separately in a bulk.

    query.setHint("eclipselink.batch", "o.department");