hibernate getCurrentSession transaction management standard sample without spring

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:

  1. If you're using Hibernate 5.2 or later, you should use the 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();
    }
    

  2. You can also use the 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();
    }
    

  3. If you're using Hibernate with JPA, you can use the 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

  4. If you're working with a web application and using Hibernate in a Servlet or JSP, you can use a 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:

    <filter>
        <filter-name>HibernateFilter</filter-name>
        <filter-class>com.example.HibernateFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HibernateFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    

    This will intercept all requests and manage transactions using Hibernate.

  5. Finally, note that while 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值