SessionFactory reuse and hibernatesession for Hibernate Performance Optimization
There are many methods to optimize Hibernate, such as caching, delayed loading, and rational SQL ing with SQL. The most basic method is to optimize SessionFactory.
SessionFactory is responsible for creating Session instances. Session is equivalent to Connection in JDBC.
SessionFactory Creation
SessionFactory is built through Configuration. Configuration constructs SessionFactory Based on Configuration information.
SessionFactory stores all mappings corresponding to the current database configuration and maintains the level-2 Cache and Statement pool. Therefore, the creation process of SessionFactory is time-consuming.
Hibernate recommends designing the Reuse Policy of SessionFactory in the Code. SessionFactory is thread-safe by default and allows concurrent calls by multiple threads.
Generally, you only need to create a SessionFactory instance in the system to avoid re-creation time and better share the second-level cache.
Reuse of SessionFactory
NetBeans provides the default HibernateUtil. java to reuse SessionFactory.
In my own project, I implemented a reusable class, which can be used as a reference:
public class HibernateSessionFactory { private final Configuration configuration; private final ServiceRegistry serviceRegistry; private final SessionFactory sessionFactory; private HibernateSessionFactory() { configuration = new Configuration().configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } public Session getSession() { return sessionFactory.openSession(); } private static class SingletonHolder { private final static HibernateSessionFactory INSTANCE = new HibernateSessionFactory(); } public static HibernateSessionFactory getInstance() { return SingletonHolder.INSTANCE; }}
The multi-threaded environment should be considered during the design. Therefore, the internal class is used to support multithreading.
Performance Testing
A simple performance test was conducted with the AB command before and after reuse. The performance was doubled, and the effect was quite obvious.
Before reuse:
After reuse:
Record, for better yourself!