I have an entity containing a List
that is thus lazy
loaded by default:
interface MyEntityRepository extends CrudRepository
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
Change your mapping from
@OneToMany(mappedBy = "bar") //lazy by default
To
@OneToMany(mappedBy = "bar", fetch = FetchType.EAGER) //lazy by default
findAllById() uses eager fetch, no customization is needed.
interface MyEntityRepository extends CrudRepository<MyEntity, Long> {
Optional<MyEntity> findAllById(long id);
}
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)
}