Home Can I change the Fetching strategy upon method call?
Reply: 1

# Can I change the Fetching strategy upon method call?

José Mendes
1#
José Mendes Published in 2018-01-11 20:20:24Z
 I was wondering if I can change the Fetching type of an Entity upon the method call, for example, if my entity has a Eager Fetching if I can fetch this entity but in a certain call I fetch using Lazy. Example: Object: Car Integer id; @ManyToOne(fetch = FetchingType.EAGER) List owners; String color; @Fech = Lazy public fetchEntity(Integer id){ }  So in this method every attribute will be fetched using LAZY instead of EAGER. Is it possible? thanks!
g00glen00b
2#
g00glen00b Reply to 2018-01-11 20:29:17Z
 If you use Spring Data, a possibility is to map everything in you entities as lazy (so all relations). And then you could use queries like this: @Query("select c from Car c left join fetch c.owners where c.id = ?1") Car findOneFetchingOwners(Long id);  Another solution is to map your table to multiple entities. For example, if you need to fetch certain fields in specific contexts, you could create an entity for each context, for example: @Entity @Table(name = "CAR") public class CarModel { // ... private String color; // ... } @Entity @Table(name = "CAR") public class CarRegistration { // ... @ManyToOne(fetch = FetchType.EAGER) private List owners; // ... }  This approach allows you to only map the fields you need and fetch them the way you want for each context, but this approach usually only works if there are really specific contexts. In this case, if you would like to know the car informtion, such as the model, color, ... you could do: carModelRepository.findOne(id);  While if you need to know the owners of the car, you could do: carRegistrationRepository.findOne(id); 
 You need to login account before you can post.
Processed in 0.349104 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO