如何将hibernate.cfg.xml配置为applicationContext.xml作为dataSource?

时间:2015-03-22 17:06:04

标签: java mysql xml hibernate spring-mvc

我的java根目录中有hibernate.cfg.xml个文件。

这是我的applicationContext.xml文件。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">

    <context:component-scan base-package="com.nought">
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="persistenceUnit" />
        <property name="dataSource" ref="dataSource" />
    </bean>

    <jpa:repositories base-package="com.nought.repository"></jpa:repositories>

</beans>

如何使用hibernate.cfg.xml文件向applicationContext.xml添加数据源。

我还想实现一个bean&#34; sessionFactory&#34;在applicationContext.xml中包含org.springframework.orm.hibernate4.LocalSessionFactoryBean的文件

如果有,我想做什么改变?

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

以下是hibernate.cfg.xml的示例以及如何使用它配置sessionFactory。

<强> cfg.xml中

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
    <property name="connection.datasource">java:comp/env/jdbc/oracle</property>
    <property name="dialect">
        org.hibernate.dialect.Oracle9iDialect
    </property>

    .. other config goes here.....
   </session-factory>
</hibernate-configuration>

添加你的applicationContext.xml。

<bean name="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

        <property name="configLocation" value="classpath:hibernate.cfg.xml" />
        <property name="mappingResources">
            <list>              
                <value>...your hbm file location...</value>
            </list>
        </property>
    </bean>