Should I use session.close() after each Hibernate Search?


#1

On the Reference Guide when we do a hibernate Search, we should start with

Transaction tx = fullTextSession.beginTransaction();

and end with

tx.commit();
session.close();

should I do it after each Hibernate Search?

because I want to get the total number and List at Service, but hibernate search is done at Dao, so if I do session.close() at Dao, I can’t get fullTextQuery.list() because the session is close.


if I don’t do session.close(),what will happen? What benefit of doing it? I only find that when I want to search A entity, I get B entity And could avoid it by give the same filed another name


#2

When saving entities, in general, and as long as you are using transactions, you are not expected to do anything differently than what you would do without Hibernate Search. (There is the one exception of session.clear(), but as long as you don’t use that, you’re fine.)

So, your question is basically a Hibernate ORM question.

If you are learning how to use Hibernate ORM, please have a look at these resources. The getting started guide and the user guide in particular can be useful. And of course you can ask questions in the Hibernate ORM category.

What is a session

In short, a session holds first-level caches and DB connections that are necessary for Hibernate ORM to work with the database. The session should only be used in one thread, and its lifespan should be as short as necessary to avoid locking resources (DB connections) unnecessarily. That being said, you will want to keep the session open to:

  • execute more DB operations (queries, entity loading, entity persisting, …)
  • use lazy-loading on the entities loaded from that session
  • combine already loaded entities with newly loaded entities (e.g. newlyLoadedEntity.setSomeAssiciation(otherEntity)). Combining entities loaded from different sessions is possible, but requires specific steps and is not trivial, so avoid it if you can.

So there’s a middle-ground to find between “one session per thread that lives forever” and “one session per DB operation”. A widespread pattern is to open one session per HTTP request to your web server, and close it after the HTTP request has been served.

Should I close the session in Hibernate ORM?

Well, it depends. The Session must be closed at some point, that’s for sure, otherwise you will leak connections and ultimately your application will just hang, because there’s isn’t any connection to the database available. But you don’t always need to close the session yourself, as some frameworks such as Spring or Java EE containers close it for you. So, refer to the documentation of your framework.