我正在使用 hibernate 进行 Maven 应用程序开发。
首次加载应用程序时, session 工厂需要花费大量时间来加载(大约 3-4 分钟),但后续 session 工厂的创建会立即发生。有人可以帮助我找出应该做出哪些改变来减少时间延迟吗?
这是 hibernate 实用程序文件:
package com.infosys.common.util;
import java.util.logging.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
/*import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;*/
// TODO: Auto-generated Javadoc
/**
* The Class HibernateUtilities.
*/
public class HibernateUtilities {
/** The Constant CONFIGURATION_LOCATION. */
private static final String CONFIGURATION_LOCATION = "com/infosys/common/util/hibernate.cfg.xml";
private static final Logger LOGGER = Logger.getLogger(HibernateUtilities.class.getName());
/** The session factory. */
private static SessionFactory sessionFactory = null;
/** The service registry. */
private static ServiceRegistry serviceRegistry;
/**
* Gets the session factory.
*
* @return the session factory
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* Creates the session factory.
*
* @return the session factory
* @throws Exception
* the exception
*/
public synchronized static SessionFactory createSessionFactory() throws Exception {
if (sessionFactory == null)
{
try {
LOGGER.info("Logger Name: " + LOGGER.getName());
// Step1 : Loading the configuration details from
// hibernate.cfg.xml
Configuration configuration = new Configuration().configure(CONFIGURATION_LOCATION);
configuration.
setProperty("hibernate.temp.use_jdbc_metadata_defaults","false");
// Step2 : Creating ServiceRegistry using the
// StandardServiceRegistryBuilder and Configuration defined in
// Step 1
serviceRegistry = new StandardServiceRegistryBuilder().configure(CONFIGURATION_LOCATION).build();
// Step3 : Creating the SessionFactory using the Configuration
// and serviceRegistry.
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
throw e;
}
}
return sessionFactory;
}
/**
* Close session factory.
*/
public static void closeSessionFactory()
{
if(sessionFactory!=null)
{
sessionFactory.close();
}
}
}
最佳答案
这很正常。 第一次配置 hibernate 并使用 session 工厂时(即当您运行程序时),它需要读取您的 hibernate 配置、所有 POJO 文件和映射文件,确保您的映射、POJO 和数据库匹配等。 所以第一次运行总是需要时间
关于java - sessionfactory创建第一次需要花费大量时间加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46910036/