Sleeping Sessions and Flow Transactions

I am working on a project that uses Hibernate3 and JDBC to connect / interact with our database (MSSQL 2008)

We are currently creating our factory session in our main class, and then we start our transaction, then we start a new thread and this thread creates connections and what does not. I will see if I can illustrate this with some pseudo code ...

public static main(String[] args){ for(...){ SessionFactory sf = new SessionFactory(); sf.getCurrentSession.beginTransaction(); CreateNewThreadedObject.run(); sf.getCurrentSession.getTransaction.commit(); } } 

My question is, is it safe? I know that sessions are not thread safe, but I do not use a session on a thread. If I use a transaction. Would it be better to go through a session with a threaded object? Any advice is appreciated!

+4
source share
2 answers

It is very important that you understand the Hibernate Sessions and the thread association best explained here:

http://community.jboss.org/wiki/Sessionsandtransactions

If you are working with a web application, I highly recommend the Open Session in View template:

https://community.jboss.org/wiki/OpenSessionInView

+5
source

You can initialize a singleton SessionFactory. It is really recommended.

Then, each thread must create a session using the factory session and complete the transaction (s).

This is really a very common pattern used in web applications. The Open Session in View template that @kvista mentions is basically a servlet filter that creates a session, starts a transaction, delegates everything that continues processing the request, and completes or rolls back the transaction at the end. And since each request is processed by a different thread in the servlet container, you can see how close the two cases are.

In your case, it would be unreasonable to execute many transactions in each thread. In fact, this is the main idea of ​​executing batch processes in a multi-threaded (ideally JTA) environment. However, one thing you should note is that a session is actually a persistence context that acts like a cache, and you should probably flush it from time to time to avoid memory leaks.

+3
source

Source: https://habr.com/ru/post/1335460/


All Articles