gpt4 book ai didi

java - Hibernate Session Factory 需要很长时间才能加载

转载 作者:行者123 更新时间:2023-11-30 08:56:25 25 4
gpt4 key购买 nike

我已经创建了自定义 session 工厂提供程序类。我在哪里设置 hibernate 属性和带注释的类。我有超过 100 个带注释的类。当我登录到应用程序时,加载 session 工厂需要很长时间。有什么办法可以解决这个问题,或者我做错了什么?请帮助我。

public class SessionFatoryProvider {

public void setNewSessionFactory(String uname,String password,HttpSession hs){

String jdbcUrl = Constants.DB_URL+Constants.DB;
java.util.Properties hibernateProperties = new java.util.Properties();
hibernateProperties.setProperty("hibernate.connection.driverClassNames", "com.mysql.jdbc.Driver");
hibernateProperties.setProperty("hibernate.connection.url", jdbcUrl);
hibernateProperties.setProperty("hibernate.connection.username", uname);
hibernateProperties.setProperty("hibernate.connection.password", password);
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
hibernateProperties.setProperty("hibernate.show_sql", "true");
hibernateProperties.setProperty("hibernate.hbm2ddl.auto","none");
hibernateProperties.setProperty("current_session_context_class","org.hibernate.context.spi.AbstractCurrentSessionContext");
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache","false");
hibernateProperties.setProperty("hibernate.cache.use_query_cache","false");

LocalSessionFactoryBean slfb = new LocalSessionFactoryBean();
slfb.setHibernateProperties(hibernateProperties);
slfb.setPackagesToScan("com.orb.bean"); //My entity class package

try {
slfb.afterPropertiesSet();
} catch (Exception e) {
e.printStackTrace();
}

SessionFactory mySessionFactory = slfb.getObject();
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(mySessionFactory);

hs.setAttribute("HibernateTransactionManager", transactionManager); //Here I am setting hibernate transaction manager in session

}

}

最佳答案

因为你已经在使用 Spring(例如 LocalSessionFactoryBean ),你应该 configure the application context这样 LocalSessionFactoryBean 就是一个单例。

因此无需手动创建 SessionFactory。这也适用于事务管理配置。

根据reference documentation , SessionFactory 是一个昂贵的对象,因为它是一个线程安全的对象,所以它应该是一个单例:

A SessionFactory is an expensive-to-create, threadsafe object, intended to be shared by all application threads. It is created once, usually on application startup, from a Configuration instance.

关于java - Hibernate Session Factory 需要很长时间才能加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28627125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com