1

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 Answers1

0

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.

Michael
  • 271
  • 4
  • 8
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Ran Marciano Feb 24 '21 at 08:14