Search code examples
springhibernatejpacaching

Does JPA open two sessions if called twice?


I hope this is a simple answer for those who are familiar with JPA/Hibernate.

So if I have a repository interface in Spring that extends the JPA interface, and I call it twice in a row to fetch a single entry in the DB, will it open two sessions? Or will the session stay open for both? Or will it load the data into memory the first time, and then use it again?

I haven't expressly enabled any caching, so I'm guessing it won't load it into memory and use it twice, but I'm not super familiar with the details behind the scenes. Everything is also set to lazy load, so not sure if that would cause the sessions to close quickly or not.

Just curious, thanks for your responses!


Solution

  • So if I have a repository interface in Spring that extends the JPA interface, and I call it twice in a row to fetch a single entry in the DB, will it open two sessions? Or will the session stay open for both?

    If both calls are part of the same transaction, only one session will be used (the one tied to the current transaction context).

    With no surrounding transaction in place, since repository methods are transactional by default, each call will be processed in a separate transaction, implying two separate sessions.

    Or will it load the data into memory the first time, and then use it again?

    If you ask for the same entity within the same transaction using findById (i.e. EntityManager.find(), the second time around it will be served from 1st-level cache.

    If you ask for the same entity using a query, the second time around the query will execute, but Hibernate will realize the entity by the retrieved id is already found in the cache, so the result will be served from 1st-level cache as well.