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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With