spring配置hibernate的sessionFactory的几种方法

本文详细介绍了使用Spring框架配置SessionFactory的三种方法:通过配置dataSource、加载hibernate.cfg.xml文件和配置jdbc.properties文件,以及纯代码配置SessionFactory。并讨论了每种方法的特点和适用场景。
摘要由CSDN通过智能技术生成


1、通过配置dataSource来配置sessionFactory

 在src 目录下放入applicationContext.xml中:

<!-- 数据库配置 -->
<bean id="mydataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    <property name="url" value="jdbc:mysql://192.168.0.2:3306/tuke_mmsmsys"></property>
    <property name="username" value="admin"></property>
    <property name="password" value="richard"></property>

    <!-- Connection Pooling Info -->
    <property name="maxActive" value="20" />
    <property name="maxIdle" value="5" />
    <property name="maxWait" value="5000" />
    <property name="validationQuery" value="select count(0) from admin" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource">
         <ref bean="mydataSource" />
    </property>
    <property name="hibernateProperties">
       <props>
             <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
             <prop key="hibernate.show_sql">true</prop>
       </props>
    </property>
    <property name="mappingDirectoryLocations">
        <list>
              <value>
                     classpath:com/tukechina/mms/pojos       
              </value>
        </list>
    </property>
    <property name="mappingResources">
        <list>
            <value>classpath*:/test/domain/MyBean.hbm.xml</value>
             <value>classpath*:/test/domain/BasicBean.hbm.xml</value>
        </list>
    </property>
    <property name="packagesToScan">
	<list>
	     <value>cn.xxx.entity</value>
	</list>
     </property>
</bean> 

补充:使用 mappingResources 属性要一个一个写 hbm 文件(“classpath*:”指向 WEB-INF/classes 目录)
     使用 mappingDirectoryLocations 属性可以指定某目录下的 hbm 文件(“classpath*:”指向 WEB-INF/classes 目录)
     使用 packagesToScan属性 这个路径可以找出com/xxx/entity根目录下的类文件

2、通过加载hibernate.cfg.xml来配置sessionFactory   
在src 目录下放入applicationContext.xml

<bean id="sessionFactory"  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
      <property name="configLocation" value="classpath:hibernate.cfg.xml">
      </property>
</bean>

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
     <session-factory name="mysql">
         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
         <property name="hibernate.connection.password">1234</property>
         <property name="hibernate.connection.url">jdbc:mysql://localhost/goodshool</property>
         <property name="hibernate.connection.username">root</property>
         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
         <property name="hibernate.show_sql">true</property>

         <!-- 最大连接数 -->
         <property name="hibernate.c3p0.max_size">20</property>
         <!-- 最小连接数 -->
         <property name="hibernate.c3p0.min_size">5</property>
         <!-- 获得连接的超时时间,如果超过这个时间,会抛出异常,单位毫秒 -->
         <property name="hibernate.c3p0.timeout">120</property>
         <!-- 最大的PreparedStatement的数量 -->
         <property name="hibernate.c3p0.max_statements">100</property>
         <!-- 每隔120秒检查连接池里的空闲连接 ,单位是秒-->
         <property name="hibernate.c3p0.idle_test_period">120</property>
         <!-- 当连接池里面的连接用完的时候,C3P0一下获取的新的连接数 -->
         <property name="hibernate.c3p0.acquire_increment">2</property>
         <!-- 每次都验证连接是否可用 -->
         <property name="hibernate.c3p0.validate">true</property>
         <mapping resource="com/shangx/pojos/User.hbm.xml" />
     </session-factory>
</hibernate-configuration>

3、通过配置jdbc.properties文件分离数据库的配置

  在src 目录下放入 jdbc.properties

Mysqljdbc.driverClassName=com.mysql.jdbc.Driver
Mysqljdbc.url=jdbc:mysql://localhost/goodshool
Mysqljdbc.username=root
Mysqljdbc.password=1234

# second cache statistics
hibernate.generate_statistics=true
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
在src 目录下放入applicationContext.xml
<bean id="propertyConfigurer"
         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
       <property name="location" value="classpath:jdbc.properties" />
</bean>

<!-- 数据库配置 -->
<bean id="mysqlDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
      <property name="driverClass">  <value>${Mysqljdbc.driverClassName}</value> </property>
      <property name="jdbcUrl"> <value>${Mysqljdbc.url}</value> </property>
      <property name="user"> <value>${Mysqljdbc.username}</value> </property>
      <property name="password"> <value>${Mysqljdbc.password}</value> </property>

         
       <property name="minPoolSize"><value>5</value></property>
       <property name="acquireIncrement"> <value>2</value></property>
       <property name="maxPoolSize"><value>20</value></property>
       <property name="maxIdleTime"><value>600</value></property>
       <property name="maxStatements" value="100"></property>
       <property name="idleConnectionTestPeriod"><value>120</value> </property>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">        
       <property name="dataSource">
             <ref bean="mysqlDataSource" />
       </property>
       <property name="hibernateProperties">
             <props>
                 <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
                 <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                 <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
             </props>
       </property>
       <property name="mappingDirectoryLocations">
             <list>
                 <value>
                     classpath:com/shangx/pojos 
                 </value>
             </list>
       </property>
</bean>
4、通过纯代码来配置sessionFactory
//默认读取hibernate.cfg.xml文件
Configuration config = new Configuration().configure();

File file = new File("src/com/oscar999/myhibernate.cfg.xml");    
Configuration config = new Configuration().configure(file);    

//在Hibernate 3中  
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); 

//在Hibernate 4中
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();  
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);  

//注解
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
SessionFactory sessionFactory = (SessionFactory)applicationContext.getBean("sessionFactory", SessionFactory.class);
Configuration configuration = new Configuration().setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver") 
				.setProperty("hibernate.connection.url", "jdbc:mysql://192.168.**.***/mall_db")
				.setProperty("hibernate.connection.username", "***")
				.setProperty("hibernate.connection.password", "***")
				.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
				.setProperty("hibernate.hbm2ddl.auto", "update");
		
ServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory factory = configuration.buildSessionFactory(registry);
Session session = factory.getCurrentSession();

上面这个方法需要导入其他的jar包。

Configuration configuration = new Configuration().addClass(com.oscar999.Usr.class);  
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();  
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);  
Session session = sessionFactory.openSession();  
session.beginTransaction();  
session.save(new Usr("uesr3"));  
session.getTransaction().commit();  
session.close();  
sessionFactory.close(); 







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值