如何正确实现Hibernate连接工厂与连接池

时间:2017-07-02 12:38:22

标签: java hibernate

我想使用Hibernate实现连接池。这是我的配置文件:

<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>

我尝试实现这个工厂类:

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;
    }
}

当我运行2个请求时,我收到错误工厂已关闭。可能我的代码没有正确实现?

1 个答案:

答案 0 :(得分:1)

您没有配置与数据源的连接。而不是:

&LT; property name =“jndi.url”&gt; jdbc / sqliteDB&lt; /性&gt;

应该是:

&LT; property name =“hibernate.connection.datasource”&gt; java:comp / env / jdbc / sqliteDB&lt; /性&gt;