Can I change the Fetching strategy upon method call?

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.


Object: Car

Integer id;
@ManyToOne(fetch = FetchingType.EAGER)
List<Owners> 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!

1 answer

  • answered 2018-01-11 20:29 g00glen00b

    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 = ?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:

    @Table(name = "CAR")
    public class CarModel {
        // ...
        private String color;
        // ...
    @Table(name = "CAR")
    public class CarRegistration {
        // ...
        @ManyToOne(fetch = FetchType.EAGER)
        private List<Owner> 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:


    While if you need to know the owners of the car, you could do: