import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
// Add Hibernate configuration properties here
return configuration.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void closeSessionFactory() {
sessionFactory.close();
}
public static void main(String[] args) {
Session session = null;
Transaction transaction = null;
try {
session = HibernateUtil.getSessionFactory().getCurrentSession();
transaction = session.beginTransaction();
// Perform database operations here
if (transaction.isActive()) {
transaction.commit();
}
} catch (Exception e) {
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
e.printStackTrace();
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
}
}
In this example, the getSessionFactory()
method is used to obtain a SessionFactory
instance. The getCurrentSession()
method is then called on the SessionFactory
instance to get the current Hibernate session, which is used to start a transaction using beginTransaction()
.
The isActive()
method is then used to check if the transaction is still active before committing it. If an exception occurs, the rollback()
method is used to rollback the transaction.
In the finally
block, the Hibernate session is closed using the close()
method if it is open, to release any resources it holds.
Note that you'll need to configure the Hibernate properties in the buildSessionFactory()
method as per your requirements.
In addition to the previous example, there are a few more things to keep in mind when using getCurrentSession()
with try-catch-finally and isActive()
for transaction management in Hibernate without using Spring:
try-with-resources
statement to automatically close the session and transaction. For example: try (Session session = HibernateUtil.getSessionFactory().getCurrentSession()) {
try (Transaction transaction = session.beginTransaction()) {
// Perform database operations here
if (transaction.isActive()) {
transaction.commit();
}
}
} catch (Exception e) {
e.printStackTrace();
}
session.getTransaction()
method to obtain the current transaction, instead of starting a new transaction with beginTransaction()
. For example: try (Session session = HibernateUtil.getSessionFactory().getCurrentSession()) {
Transaction transaction = session.getTransaction();
try {
transaction.begin();
// Perform database operations here
if (transaction.isActive()) {
transaction.commit();
}
} catch (Exception e) {
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
javax.persistence.EntityManager
interface instead of org.hibernate.Session
. The EntityManager
provides similar transaction management methods like getTransaction()
, commit()
, and rollback()
. For example: EntityManager entityManager = HibernateUtil.getSessionFactory().createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
try {
transaction.begin();
// Perform database operations here
if (transaction.isActive()) {
transaction.commit();
}
} catch (Exception e) {
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
e.printStackTrace();
} finally {
if (entityManager != null && entityManager.isOpen()) {
entityManager.close();
}
}
These are some of the variations you can use when using getCurrentSession()
with try-catch-finally and isActive()
for transaction management in Hibernate without using Spring
Filter
or a Servlet
to manage transactions for each request. The Filter
intercepts incoming requests and opens a Hibernate session and transaction for each request. After processing the request, the Filter
commits or rolls back the transaction and closes the session. For example: import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class HibernateFilter implements Filter {
private SessionFactory sessionFactory;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
sessionFactory = HibernateUtil.getSessionFactory();
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.getCurrentSession();
transaction = session.beginTransaction();
// Pass the request to the next filter or servlet
chain.doFilter(request, response);
if (transaction.isActive()) {
transaction.commit();
}
} catch (Exception e) {
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
e.printStackTrace();
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
}
@Override
public void destroy() {
HibernateUtil.closeSessionFactory();
}
}
In this example, the init()
method initializes the sessionFactory
variable by calling HibernateUtil.getSessionFactory()
. In the doFilter()
method, a Hibernate session and transaction are obtained using getCurrentSession()
and beginTransaction()
respectively. The chain.doFilter()
method is called to pass the request to the next filter or servlet. After processing the request, the transaction is committed or rolled back, and the session is closed in the finally
block. The destroy()
method is used to close the Hibernate session factory.
To use this Filter
, you need to map it to a URL pattern in the web.xml
file of your web application:
HibernateFilter
com.example.HibernateFilter
HibernateFilter
/*
This will intercept all requests and manage transactions using Hibernate.
getCurrentSession()
is a convenient way to obtain a Hibernate session in a thread-local context, it has some limitations. For example, it doesn't work with a separate thread or a long-running process. In such cases, you need to use openSession()
to obtain a new session and manage transactions manually. Additionally, getCurrentSession()
may throw exceptions if the session is not open or if the transaction has already been committed or rolled back. Therefore, you should always use try-catch-finally
blocks and isActive()
checks to manage transactions safely and reliably.Spring Transaction Management: @Transactional In-Depth