2012-11-30 97 views
6

我爲我的web應用程序使用Spring 3.1.2和Hibernate 4.1.7。我想現在配置這兩個。我有我的hibernate.cfg.xml文件:爲什麼在Spring-Hibernate配置中同時配置dataSource和sessionFactory?

<hibernate-configuration> 
    <session-factory> 
     <property name="connection.url">jdbc:mysql://localhost:3306/test</property> 
     <property name="connection.username">root</property> 
     <property name="connection.password">root</property> 
     <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 
     <property name="hibernate.connection.pool_size">10</property> 
     <property name="hibernate.connection.autocommit">false</property> 
     <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> 
     <!-- 
     <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property> 
     --> 
     <property name="hibernate.show_sql">true</property> 
     <property name="hibernate.hbm2ddl.auto">update</property>  
    </session-factory> 
</hibernate-configuration> 

webapp-servlet.xml Spring配置文件:

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

<bean id = "dataSource" class = "org.apache.commons.dbcp.BasicDataSource"> 
    <property name = "driverClassName" value = "com.mysql.jdbc.Driver" /> 
    <property name = "url" value = "jdbc:mysql://localhost:3306/test" /> 
    <property name = "username" value = "root" /> 
    <property name = "password" value = "root" /> 
    <property name = "maxActive" value = "10" /> 
</bean> 
</beans> 
  1. 爲什麼我需要配置一個DataSource bean時需要的所有數據都已經包含在hibernate配置文件? Hibernate是否有一些可以使用的默認值?
  2. 什麼是其他DataSource我可以使用?
  3. 我是否缺少任何其他bean或配置參數/屬性來使用我的應用程序進行休眠?
+1

從你的'hibernate.cfg所有的配置選項。'LocalSessionFactoryBean'上有'xml',喜歡後者並在Hibernate配置中跳過它們。 –

+0

好的。但我仍然只希望他們在一個地方,而不是在不同的文件或豆類重複。 –

+2

這就是我所說的,從'hibernate.cfg.xml'中刪除數據源配置並將其保留在Spring XML中。您稍後可以使用相同的'dataSource' bean,例如在'JdbcTemplate'中。 –

回答

8
  1. 你不需要兩者。您可以擺脫hibernate.cfg.xml並配置LocalSessionFactoryBean中的所有內容,或按原樣重新使用現有的hibernate.cfg.xml(在這種情況下,您無需在Spring配置中配置DataSource)。

  2. 您有以下選擇:

    • 使用embedded database - 這是很好的測試和學習的目的

    • 使用DriverManagerDataSource - 這是一個簡單的非合併數據源,可用於測試, (不建議用於生產用途)

    • 使用連接池,如DBCP或c3p0

    • 如果部署到應用服務器,您可以使用應用程序服務器using JNDI

  3. 您當前的配置足以提供連接池,但它缺乏支持的Spring transaction management。爲了使它,你需要

    • 聲明HibernateTransactionManager

    • 添加<tx:annotation-driven>,使聲明式事務管理(@Transactional

    • 聲明TransactionTemplate,如果你想使用編程式事務管理(使用克服聲明式交易管理的侷限性)

    • 另外不要忘記除去從Hibernate配置與交易相關的特性,因爲它們可能與Spring的事務管理衝突

+0

默認情況下不休眠使用C3P0嗎?感謝交易管理,我也在尋找。接受爲完整答案。 –

+1

@SotiriosDelimanolis:如果你使用'hibernate.cfg.xml'配置它 - 是的。但是Spring從'DataSource'配置中分離了Hibernate配置,因此可以使用不同的'DataSource'實現。 – axtavt

相關問題