简体   繁体   中英

How to properly implement Hibernate connection factory with connection pool

I want to implement connection pool using Hibernate. This is my configuration file:

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <property name="jndi.url">jdbc/sqliteDB</property>
        <property name="hibernate.dialect">org.hibernate.dialect.SQLiteDialect</property>
        <property name="hibernate.connection.driver_class">org.sqlite.JDBC</property>
        <property name="hibernate.connection.release_mode">auto</property>
        <property name="current_session_context_class">thread</property>
        <property name="hibernate.connection.autoReconnect">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <mapping class="com.web.models.SystemUsers"/>
    </session-factory>
</hibernate-configuration>

I tried to implement this factory class:

public class HibernateUtil
{
    private static final SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    static
    {
        try
        {
            StandardServiceRegistry standardRegistry
                = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
            Metadata metaData
                = new MetadataSources(standardRegistry).getMetadataBuilder().build();
            sessionFactory = metaData.getSessionFactoryBuilder().build();
        }
        catch (Throwable th)
        {
            System.err.println("Enitial SessionFactory creation failed" + th);
            throw new ExceptionInInitializerError(th);
        }
    }

    public static SessionFactory getSessionFactory()
    {
        return sessionFactory;
    }
}

When I run 2 requests I get error factory is closed. Probably my code is not implement properly?

You didn't configured your connection to datasource. Instead of:

< property name="jndi.url">jdbc/sqliteDB < /property>

should be :

< property name="hibernate.connection.datasource">java:comp/env/jdbc/sqliteDB< /property>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM