2

I am a new person for Hibernate & JPA. Now, I am curious about the running performance between FetchType.EAGER and Left Join Fetch.

For example.

  1. Option 1
@Entity
@Table(name = "EMPLOYEE")
public class Employee {

    @OneToMany(mappedBy = "employee", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Set<Email> emails;
}
em.find(Employee.class, id)

the hibernate query like:

select
   ...
from
    EMPLOYEE employee0_
left outer join
    Email email1_
        on employee0_.employee_id=email1_.employee_id
where
    employee0_.employee_id=?
  1. Option 2 if I change the annotation of email on employee from eager into lazy
@Entity
@Table(name = "EMPLOYEE")
public class Employee {

    @OneToMany(mappedBy = "employee", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private Set<Email> emails;
}

em.createQuery ("select e from Employee e left join fetch e.emails ee where e.id=:id", Employee.class);

the hibernate query like:

select
   ...
from
    EMPLOYEE employee0_
left outer join
    Email email1_
        on employee0_.employee_id=email1_.employee_id
where
    employee0_.employee_id=?

So, my question is that does the above two is equal to the running performance perspective because the SQL is the same.

Many thanks.

Kensin
  • 21
  • 2
  • Yes. There will be a difference in performance when you load employees without a left join fetch, because you don't care about their emails. Using eager fetching will still load the emails although they're unnecessary. – JB Nizet May 19 '19 at 11:04
  • 1
    Possible duplicate of [Difference between FetchType LAZY and EAGER in Java Persistence API?](https://stackoverflow.com/questions/2990799/difference-between-fetchtype-lazy-and-eager-in-java-persistence-api) – Butiri Dan May 19 '19 at 11:05
  • Note that in some cases, `EAGER` vs `JOIN FETCH` might differ in performance because the JPA provider might choose a strategy different than a SQL `JOIN` to fetch related entities (e. g. a subselect). Hibernate lets you force a particular strategy using the `@Fetch` annotation – crizzis May 19 '19 at 11:51
  • @crizzis Thank you for your comment. could you plz show some example. This one really makes me exhausted, although I have googled a lot. – Kensin May 20 '19 at 10:06
  • What I meant is that in some cases, the provider might choose to fetch related entities using e.g. a subselect when using `@OneToMany(fetch = EAGER)`. In Hibernate, you can force the fetching strategy using `@OneToMany(fetch = EAGER) @Fetch(JOIN)`. As for a specific example when a different strategy might be selected by the provider, I don't really have one readily available, it is up to the JPA implementation to decide – crizzis May 20 '19 at 10:43

0 Answers0