Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 292
membersound Avatar asked Aug 06 '15 11:08

membersound


People also ask

Does JpaRepository extends CrudRepository?

JPA repository extends CrudRepository and PagingAndSorting repository. It inherits some finders from crud repository such as findOne, gets and removes an entity.

What is difference between CrudRepository and JpaRepository interfaces in Spring data JPA?

Their main functions are: CrudRepository mainly provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sorting records. JpaRepository provides some JPA-related methods such as flushing the persistence context and deleting records in a batch.

What is true about CrudRepository and JpaRepository in Spring data JPA?

CrudRepository provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.


2 Answers

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)
}
like image 87
Tomasz Fijałkowski Avatar answered Sep 28 '22 06:09

Tomasz Fijałkowski


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

like image 26
Luis Rocha Avatar answered Sep 28 '22 05:09

Luis Rocha