javahibernatespring-bootjpaspring-data-jpa

How Spring Boot Handle Hibernate Session?


I see with the Spring Boot you don't need to open and close the hibernate session.

But for the understanding purpose how it is working internally, On which layer it is opening the hibernate session and when it is closing.

I created one POC. I have one Spring boot application it has two Entity One is Customer and other is Address and there is one to Many relation between Customer and Address.

And I have one two Apis one is adding record and other is fetching all the records. These APis are there in the CustomerEndpoint and it is annotated with

@RestController
@RequestMapping(value="/customer").

And also created CustomerRepository which extends CrudRepository for saving and fetching the Customer records.

So as per my understanding while fetching the Customer using CustomerRepository inside CustomerEndpointclass should throw LazyInitialization error when we will say customer.getAddress(as its fetchtype is LAZY). But it is not throwing any error, it is working properly.

I was thinking the hibernate session not be there in the CustomerEndpoint class.

Can anyone help me how this Hibernate session is maintained by Spring boot?

As everybody is thinking it as a duplicate of another question but my question is not top of their explanation as according to them session is valid till the Repository so according to that i should get LazyInitialization exception while saying customer.getAddress inside CustomerEndpoint as it is not a Repository but i am not getting any Exception


Solution

  • First of all it is not a good practice to use Repository layer in your Presentation layer.

    OSIV (Open Session in View) is enabled by default in Spring Boot, and OSIV is really a bad idea from a performance and scalability perspective.

    Because of this you are not getting the exception and able to work in your presentation layer. Check by putting the follwoings in your application.properties file

    spring.jpa.open-in-view=false
    

    You can refer OSIV AntiPattern for more details