11.3.2. Non-managed Environment
If a Hibernate persistence layer runs in a non-managed environment, database connections are usually handled by simple (i.e., non-DataSource) connection pools from which Hibernate obtains connections as needed. The session/transaction handling idiom looks like this:
// Non-managed environment idiom Session sess = factory.openSession(); Transaction tx = null; try { tx = sess.beginTransaction(); // do some work ... tx.commit(); } catch (RuntimeException e) { if (tx != null) tx.rollback(); throw e; // or display error message } finally { sess.close(); }
You do not have to
flush()
the Session
explicitly: the call to commit()
automatically triggers the synchronization depending on the flushing set for the session. A call to close()
marks the end of a session. The main implication of close()
is that the JDBC connection will be relinquished by the session. This Java code is portable and runs in both non-managed and JTA environments.
As outlined earlier, a much more flexible solution is Hibernate's built-in "current session" context management:
// Non-managed environment idiom with getCurrentSession() try { factory.getCurrentSession().beginTransaction(); // do some work ... factory.getCurrentSession().getTransaction().commit(); } catch (RuntimeException e) { factory.getCurrentSession().getTransaction().rollback(); throw e; // or display error message }
You will not see these code snippets in a regular application; fatal (system) exceptions should always be caught at the "top". In other words, the code that executes Hibernate calls in the persistence layer, and the code that handles
RuntimeException
(and usually can only clean up and exit), are in different layers. The current context management by Hibernate can significantly simplify this design by accessing a SessionFactory
. Exception handling is discussed later in this chapter.
You should select
org.hibernate.transaction.JDBCTransactionFactory
, which is the default, and for the second example select "thread"
as your hibernate.current_session_context_class
.