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)
?
JPA repository extends CrudRepository and PagingAndSorting repository. It inherits some finders from crud repository such as findOne, gets and removes an entity.
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.
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.
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)
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With