1

I created the entity Org that has a one to one mapping with OrgHV

@Table(name="ORG_CHART")
@Entity
public class Org {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="ORG_ID")
    private int id;

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "ORG_ID")
    private OrgHV orgHV;
    //getters and Setters
}

In the service I retrieved all entities of Org using Spring data Jpa repo and because of lazy loading OrgHV will not be fetched until I call org.getOrgHV(). The problem is I am doing so after I called repo.findAll(), so the session/transaction is closed (correct me if I am wrong)? Why the code is working fine, why LazyInitializationException is not thrown?

public orgService()
{
   List<Org> orgs = orgRepo.findAll();
   for (Org org: orgs) 
   {  
      orgRepo.findAll();  
      OrgHV orgHv = org.getOrgHV();
      System.out.pringLn(orgHv.getId());
   }
}
jwpol
  • 573
  • 3
  • 17
Phyzia
  • 13
  • 4
  • Does this answer your question? [Making a OneToOne-relation lazy](https://stackoverflow.com/questions/1444227/making-a-onetoone-relation-lazy) – Willian Dec 30 '19 at 02:23
  • I am also curious why LazyInitializationException is not thrown in this example. FetchType is LAZY, transaction is finished, so why it is working? – jwpol Sep 29 '20 at 21:33

1 Answers1

0

Exception is not thrown, because of spring.jpa.open-in-view property, by default set to true (source), which registers OpenEntityManagerInViewInterceptor. This binds a JPA EntityManager to the thread for the entire processing of the request, so even though findAll() method finishes as well as the transaction, still lazy loaded fields can be fetched.

As stated in the doc

Spring web request interceptor binds a JPA EntityManager to the thread for the entire processing of the request. Intended for the "Open EntityManager in View" pattern, i.e. to allow for lazy loading in web views despite the original transactions already being completed.

You are even warned about that when Spring-Boot application starts (if that property is not explicitly set):

WARN 8363 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning

If you want to see the expected exception, set in the application.properties

spring.jpa.open-in-view=false
jwpol
  • 573
  • 3
  • 17