创建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包。


你可能感兴趣的:(创建LocalSessionFactory对象)