DEV Community

Salad Lam
Salad Lam

Posted on

Function of OpenEntityManagerInViewInterceptor Spring MVC interceptor

Notice

I wrote this article and was originally published on Qiita on 13 September 2019.


Function of OpenEntityManagerInViewInterceptor

  1. Create a EntityManager instance and bind it to thread when start processing HTTP request
  2. Close the EntityManager instance created before when finish processing HTTP request

Why need it?

Assume entity A, its property 'type' set to entity B. Entity A is created by EntityManager, which is set to lazy loading. This EntityManager instance may be closed if a transaction loading entity A is finished. And then property 'type' of enitiy A is accessed on view layer. Since entity B is a proxy instance and being load if necessary. In order to load entity B, EntityManager which created entity A is necessary. At moment on view layer that EntityManager is gone. As result exception occurs.

If OpenEntityManagerInViewInterceptor is enabled, the EntityManager instance is available at the moment on view layer.

How to enable it in Spring Boot?

OpenEntityManagerInViewInterceptor is enabled by default. Or you may enable it explicitly by adding below line in property file 'application.properties'.

spring.jpa.open-in-view=true
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay