How to force eager loading with CrudRepository in spring-data?

前端 未结 4 1963
抹茶落季
抹茶落季 2021-01-11 10:43

I have an entity containing a List that is thus lazy loaded by default:

interface MyEntityRepository extends CrudRepository

        
相关标签:
4条回答
  • 2021-01-11 11:24

    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

    0 讨论(0)
  • 2021-01-11 11:26

    Change your mapping from

    @OneToMany(mappedBy = "bar") //lazy by default
    

    To

    @OneToMany(mappedBy = "bar", fetch = FetchType.EAGER) //lazy by default
    
    0 讨论(0)
  • 2021-01-11 11:28

    findAllById() uses eager fetch, no customization is needed.

      interface MyEntityRepository extends CrudRepository<MyEntity, Long> {        
        Optional<MyEntity> findAllById(long id);
    }
    
    0 讨论(0)
  • 2021-01-11 11:44

    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)
    }
    
    0 讨论(0)
提交回复
热议问题