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)
}
Share:
12,102

Related videos on Youtube

membersound
Author by

membersound

JEE + Frameworks like Spring, Hibernate, JSF, GWT, Vaadin, SOAP, REST.

Updated on September 05, 2022

Comments

  • membersound
    membersound over 1 year

    I have an entity containing a List that is thus lazy 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
      Jebil over 8 years
      @OneToMany(fetch=FetchType.EAGER) will this help ?
    • membersound
      membersound over 8 years
      I know I can force the eager mode like this. But I want to stick to the lazy default and just force eager on all lists on one specific select.
    • Jebil
      Jebil over 8 years
      or you can use MyEntity p = (MyEntity) sess.get(MyEntity.class, id); Hibernate.initialize(p.getBars());
    • membersound
      membersound over 8 years
      So that would imply writing my own criterea. Which is fine in general, but I hope spring-data would bring something for this.
  • membersound
    membersound over 6 years
    To 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
    Tomasz Fijałkowski almost 6 years
    This solution generate more then one query.
  • Tien Do Nam
    Tien Do Nam about 4 years
    Can you show the source? I think that findBy and findAllBy does not make any difference.