创建LocalSessionFactory对象

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 {

@Autowired
private Environment env;

@Bean
public 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.Driver
jdbc.url=jdbc\:mysql\://localhost/public_cms?useUnicode\=true&characterEncoding\=UTF-8&zeroDateTimeBehavior\=round
jdbc.username=root
jdbc.password=root
cpool.checkoutTimeout=20000
cpool.autoCommitOnClose=true
cpool.minPoolSize=5
cpool.maxPoolSize=20
cpool.maxIdleTime=25
cpool.maxIdleTimeExcessConnections=1800
cpool.acquireIncrement=10
#hibernate.dialect=com.sanluan.common.dialect.MyDialect
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=false
hibernate.query.substitutions=true 1, false 0
hibernate.jdbc.fetch_size=50
hibernate.jdbc.batch_size=50
hibernate.transaction.coordinator_class=jdbc
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_query_cache=true
hibernate.cache.provider_configuration_file_resource_path=ehcache.xml
hibernate.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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值