EntityGraph not fetching relations provided dynamically

817 Views Asked by At

I am trying to load lazy attributes of the entity using spring JPA repository and Entity graph , EntityGraph is not fetching relations provided dynamically , instead it fetches attributes as per the static fetch type defined in entity for that attribute.

@Repository
@Transactional
public interface SampleRepository extends JpaRepository<Sample,Long> {

    @EntityGraph(attributePaths = {"oneToOneLazyRelation1","oneToOneLazyRelation2"})
    List<Sample> findAllByCustomer(Customer customer);

}

@Entity
public class Sample {

    @id
    private Long id;

    @OneToOne(cascade = CascadeType.ALL ,fetch=FetchType.LAZY)
    @LazyToOne(value = LazyToOneOption.NO_PROXY)
    @LazyGroup("oneToOneLazyRelation1")
    private OneToOneLazyRelation1 oneToOneLazyRelation1;
    
    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @LazyToOne(value = LazyToOneOption.NO_PROXY)
    @LazyGroup("oneToOneLazyRelation2")
    private OneToOneLazyRelation2 oneToOneLazyRelation2;
}

Using hibernate - 5.2.17.Final , Spring - 4.3.20.RELEASE , Spring data JPA - 1.11.22.RELEASE

1

There are 1 best solutions below

1
On

The Hibernate User Guide states

However, if you really need to use a bidirectional association and want to make sure that this is always going to be fetched lazily, then you need to enable lazy state initialization bytecode enhancement and use the @LazyToOne annotation as well."

see also https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#associations-one-to-one-bidirectional-lazy

So the above annotation LazyToOne leads to the fact that the associations are always loaded lazily.