Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FetchMode join makes no difference for ManyToMany relations in spring JPA repositories

I'm trying to do this:

//...
class Person {
    @ManyToMany(fetch = FetchType.EAGER)
    @Fetch(FetchMode.JOIN)
    private Set<Group> groups;
//...
}

it generates n+1 queries when I do personRepository.findAll(); through a Spring JPA repository, just as if I didn't have any @Fetch set. (One query first to get all the persons, and then one query per person to fetch the groups).

Using @Fetch(FetchMode.SUBSELECT) works, though! It only generates 2 queries. (One for all persons, and then one for the groups). So hibernate reacts to some fetch parameters, just not the JOIN.

I have also tried removing the EAGER fetching with no luck.

//...
class Person {
    @ManyToMany()
    @Fetch(FetchMode.JOIN)
    private Set<Group> groups;
//...
}

I am using Spring JPA, and this is the code for my repository:

public interface PersonRepository extends JpaRepository<Person, Long> {
}

Does JOIN just not work through Spring JPA, or am I doing something wrong?

like image 405
Matsemann Avatar asked Sep 19 '13 10:09

Matsemann


1 Answers

Going through many forums and blogs to read for your problem (I guess you might have done that before posting it here) I too think that

@Fetch(FetchMode.JOIN) will be ignored if you use the Query interface (e.g.: session.createQuery()) but it will be properly used if you use the Criteria interface.

This is practically a bug in Hibernate which was never resolved. It is unfortunate because a lot of applications use the Query interface and cannot be migrated easily to the Criteria interface.

If you use the Query interface you always have to add JOIN FETCH statements into the HQL manually.

References Hibernate Forum Spring Forum Similar Question 1

like image 130
DarkHorse Avatar answered Oct 18 '22 08:10

DarkHorse