博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
创建LocalSessionFactory对象
阅读量:5887 次
发布时间:2019-06-19

本文共 7262 字,大约阅读时间需要 24 分钟。

  hot3.png

Spring里面的SessionFactory一般如下配备在xml中:

     

  1.  <bean id="sessionFactory"  

  2.         class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  

  3.         <property name="configLocation"  

  4.             value="classpath:hibernate.cfg.xml">  

  5.         </property>  

  6.     </bean>  

此处我们可以看到我们配置的Sessionfactory,但是class却是LocalSessionFactoryBean,和我们需要的貌似不符,实际上由于LocalSessionFactoryBean实现了

FactoryBean

这个类,Spring中会在你调用Sessionfactory的时候通过调用LocalSessionFactoryBean.getObject来返回Sessionfactory。

以下是硬编码的方式获取sessionfactory:

  

public class ApplicationConfig {@Autowiredprivate Environment env;@Beanpublic SessionFactory sessionFactory() throws IOException {    LocalSessionFactoryBean bean = new LocalSessionFactoryBean();    bean.setDataSource(dataSource());    bean.setPackagesToScan(new String[] { "com.publiccms.entities" });    Properties hibernateProperties = new Properties();    hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));    hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));    hibernateProperties.setProperty("hibernate.query.substitutions", env.getProperty("hibernate.query.substitutions"));    hibernateProperties.setProperty("hibernate.jdbc.fetch_size", env.getProperty("hibernate.jdbc.fetch_size"));    hibernateProperties.setProperty("hibernate.jdbc.batch_size", env.getProperty("hibernate.jdbc.batch_size"));    hibernateProperties.setProperty("hibernate.cache.region.factory_class",            env.getProperty("hibernate.cache.region.factory_class"));    hibernateProperties.setProperty("hibernate.cache.use_second_level_cache",            env.getProperty("hibernate.cache.use_second_level_cache"));    hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));    hibernateProperties.setProperty("hibernate.transaction.coordinator_class",            env.getProperty("hibernate.transaction.coordinator_class"));    hibernateProperties.setProperty("hibernate.cache.provider_configuration_file_resource_path",            env.getProperty("hibernate.cache.provider_configuration_file_resource_path"));    hibernateProperties.setProperty("hibernate.search.default.directory_provider",            env.getProperty("hibernate.search.default.directory_provider"));    hibernateProperties.setProperty("hibernate.search.default.indexBase", getDataFilePath() + "/indexes");    bean.setHibernateProperties(hibernateProperties);    bean.afterPropertiesSet();    return  bean.getObject(); }}

 

  dbconfig.properties

jdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc\:mysql\://localhost/public_cms?useUnicode\=true&characterEncoding\=UTF-8&zeroDateTimeBehavior\=roundjdbc.username=rootjdbc.password=rootcpool.checkoutTimeout=20000cpool.autoCommitOnClose=truecpool.minPoolSize=5cpool.maxPoolSize=20cpool.maxIdleTime=25cpool.maxIdleTimeExcessConnections=1800cpool.acquireIncrement=10#hibernate.dialect=com.sanluan.common.dialect.MyDialecthibernate.dialect=org.hibernate.dialect.MySQLDialecthibernate.show_sql=falsehibernate.query.substitutions=true 1, false 0hibernate.jdbc.fetch_size=50hibernate.jdbc.batch_size=50hibernate.transaction.coordinator_class=jdbchibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactoryhibernate.cache.use_second_level_cache=falsehibernate.cache.use_query_cache=truehibernate.cache.provider_configuration_file_resource_path=ehcache.xmlhibernate.search.default.directory_provider=org.hibernate.search.store.impl.FSDirectoryProvider

  我们通过查看LocalSessionfactoryBean的源码,

public SessionFactory getObject() {    return this.sessionFactory;}

  可以看到sessionfactory是通过getObject来返回的。在对

LocalSessionFactoryBean

   配置hibernateproperties之后,需要调用

afterPropertiesSet()

   方法,不然sessionfactory将是空值,方法源码如下:

public void afterPropertiesSet() throws IOException {    LocalSessionFactoryBuilder sfb = new LocalSessionFactoryBuilder(this.dataSource, this.resourcePatternResolver);    Resource[] var2;    int var3;    int var4;    Resource resource;    if(this.configLocations != null) {        var2 = this.configLocations;        var3 = var2.length;        for(var4 = 0; var4 < var3; ++var4) {            resource = var2[var4];            sfb.configure(resource.getURL());        }    }    if(this.mappingResources != null) {        String[] var7 = this.mappingResources;        var3 = var7.length;        for(var4 = 0; var4 < var3; ++var4) {            String var8 = var7[var4];            ClassPathResource file = new ClassPathResource(var8.trim(), this.resourcePatternResolver.getClassLoader());            sfb.addInputStream(file.getInputStream());        }    }    if(this.mappingLocations != null) {        var2 = this.mappingLocations;        var3 = var2.length;        for(var4 = 0; var4 < var3; ++var4) {            resource = var2[var4];            sfb.addInputStream(resource.getInputStream());        }    }    if(this.cacheableMappingLocations != null) {        var2 = this.cacheableMappingLocations;        var3 = var2.length;        for(var4 = 0; var4 < var3; ++var4) {            resource = var2[var4];            sfb.addCacheableFile(resource.getFile());        }    }    if(this.mappingJarLocations != null) {        var2 = this.mappingJarLocations;        var3 = var2.length;        for(var4 = 0; var4 < var3; ++var4) {            resource = var2[var4];            sfb.addJar(resource.getFile());        }    }    if(this.mappingDirectoryLocations != null) {        var2 = this.mappingDirectoryLocations;        var3 = var2.length;        for(var4 = 0; var4 < var3; ++var4) {            resource = var2[var4];            File var9 = resource.getFile();            if(!var9.isDirectory()) {                throw new IllegalArgumentException("Mapping directory location [" + resource + "] does not denote a directory");            }            sfb.addDirectory(var9);        }    }    if(this.entityInterceptor != null) {        sfb.setInterceptor(this.entityInterceptor);    }    if(this.implicitNamingStrategy != null) {        sfb.setImplicitNamingStrategy(this.implicitNamingStrategy);    }    if(this.physicalNamingStrategy != null) {        sfb.setPhysicalNamingStrategy(this.physicalNamingStrategy);    }    if(this.jtaTransactionManager != null) {        sfb.setJtaTransactionManager(this.jtaTransactionManager);    }    if(this.currentTenantIdentifierResolver != null) {        sfb.setCurrentTenantIdentifierResolver(this.currentTenantIdentifierResolver);    }    if(this.entityTypeFilters != null) {        sfb.setEntityTypeFilters(this.entityTypeFilters);    }    if(this.hibernateProperties != null) {        sfb.addProperties(this.hibernateProperties);    }    if(this.annotatedClasses != null) {        sfb.addAnnotatedClasses(this.annotatedClasses);    }    if(this.annotatedPackages != null) {        sfb.addPackages(this.annotatedPackages);    }    if(this.packagesToScan != null) {        sfb.scanPackages(this.packagesToScan);    }    this.configuration = sfb;    this.sessionFactory = this.buildSessionFactory(sfb);}
protected SessionFactory buildSessionFactory(LocalSessionFactoryBuilder sfb) {    return sfb.buildSessionFactory();}

 这样就可以获取到我们一般意义上的sessionfactory了,如果在此过程中出现class not found:org/hibernate/boot/spi/SessionFactoryOptions 可能你使用的hibernate-core的jar包版本比较低,需要更新新的jar包。

转载于:https://my.oschina.net/guanhe/blog/656053

你可能感兴趣的文章
Linux Kernel中断子系统来龙去脉浅析【转】
查看>>
Linux NFS服务器的安装与配置
查看>>
Ada boost学习
查看>>
Unity中SendMessage和Delegate效率比较
查看>>
Linux下EPoll通信模型简析
查看>>
react-native 制作购物车ShopCart
查看>>
Linux服务器 java生成的图片验证码乱码问题
查看>>
【转】QT中QDataStream中浮点数输出问题
查看>>
mongodb3.2配置文件yaml格式 详解
查看>>
RecycleView
查看>>
一致性哈希算法(consistent hashing)
查看>>
centOS_5.4_安装Open×××
查看>>
Spring Security OAuth2 开发指南
查看>>
TCP
查看>>
参观迅达云成公司有感
查看>>
mount挂载NTFS失败
查看>>
CentOS6.5安装MariaDB10.0.15编译安装和多实例管理配置
查看>>
lua 自定义lib
查看>>
U盘安装centos6.5
查看>>
protobuf消息的自动派发
查看>>