我使用这个Java代码在JSF应用程序和SQLite数据库中使用Hibernate进行SQL查询:
Hibernate配置文件:
<hibernate-configuration>
<session-factory>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.connection.datasource">java:comp/env/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;
}
}
我使用此代码调用Hibernate工厂类:
private List<SystemUserObj> generateSystemUsers()
{
try (SessionFactory sessFact = HibernateUtil.getSessionFactory())
{
Session session = sessFact.getCurrentSession();
Transaction tr = session.beginTransaction();
List<SystemUsers> dataList = session.createQuery("from SystemUsers").list();
for (SystemUsers user : dataList)
{
........
}
session.flush();
tr.commit();
}
return list;
}
然后我第一次正确加载数据时打开网页,但是当我第二次打开页面时出错:
Caused by: java.lang.IllegalStateException: EntityManagerFactory is closed
你知道如何解决这个问题吗? 可能我的工厂类没有正确实施?
另外我如何重构Factory代码以便我可以同时发出多个请求?