How to force eager loading with CrudRepository in spring-data?
12,102
Solution 1
I needed this too and as I'm calling the dao inside a service object that is insise a transaction I call call the get method so no exception and I was able to fetch the records. Something like in java 8:
public ProductEntity findProduct(int id) {
ProductEntity p = productRepository.findOne(id);
p.getPresentations().stream().count();
return p;
}
p.getPresentations().stream().count();
will force the fetch, I know is not a clean way to do it but it gets the job done in the mean time
Solution 2
You can force eager fetch writing custom HQL query with left join fetch
, eg:
interface MyEntityRepository extends CrudRepository<MyEntity, Long> {
@Query("select e from MyEntity e left join fetch e.bar b where e.id = ?1")
MyEntity findOne(long id)
}
Related videos on Youtube

Author by
membersound
JEE + Frameworks like Spring, Hibernate, JSF, GWT, Vaadin, SOAP, REST.
Updated on September 05, 2022Comments
-
membersound 9 months
I have an entity containing a
List
that is thuslazy
loaded by default:interface MyEntityRepository extends CrudRepository<MyEntity, Long> { } @Entity public class MyEntity { @Id private Long id; @OneToMany(mappedBy = "bar") //lazy by default private List<Bar> bars; } @Entity public class Bar { //some more }
Question: How can I force eager loading when executing
repository.findOne(id)
?-
Jebil almost 8 years
@OneToMany(fetch=FetchType.EAGER)
will this help ? -
membersound almost 8 yearsI know I can force the
eager
mode like this. But I want to stick to thelazy
default and just force eager on all lists on one specific select. -
Jebil almost 8 yearsor you can use
MyEntity p = (MyEntity) sess.get(MyEntity.class, id); Hibernate.initialize(p.getBars());
-
membersound almost 8 yearsSo that would imply writing my own criterea. Which is fine in general, but I hope spring-data would bring something for this.
-
-
membersound over 5 yearsTo quote myself: "I know I can force the eager mode like this. But I want to stick to the lazy default and just force eager on [...] one specific select"
-
Tomasz Fijałkowski almost 5 yearsThis solution generate more then one query.
-
Tien Do Nam about 3 yearsCan you show the source? I think that findBy and findAllBy does not make any difference.