2012-02-12 34 views
2

如你所知,在Spring中的ApplicationContext,我們可以定義從persistence.xml中的entityManagerFactory豆就像:我可以在spring應用程序上下文中從jpa獲取jdbc數據源嗎?

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 
    <property name="persistenceUnitName" value="MyUnit" /> 
    <property name="jpaVendorAdapter"> 
     <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> 
      <property name="showSql" value="true" /> 
      <property name="generateDdl" value="false" /> 
      <property name="database" value="MYSQL" /> 
     </bean> 
    </property> 
</bean> 
現在

如果我想初始化數據庫如下:

<jdbc:initialize-database data-source="myDataSource" enabled="true"> 
    <jdbc:script location="classpath*:com/myapp/data*.sql"/> 
</jdbc:initialize-database> 

應該我必須配置其他數據源bean爲它?或者我可以參考上面定義的emf,或者可以參考persistence.xml?

+0

@skaffman:這是從春天參考:12.9.1使用Spring XML 初始化數據庫實例「如果你想初始化一個數據庫,你可以提供一個DataSource bean的引用,使用初始化spring-jdbc命名空間中的-datasource標記:「 – Ralph 2012-02-12 11:08:40

回答

1
<!-- use jndi lookup, or define it by your selfe --> 
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/myDataSource" /> 

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

    <!-- this is important to connect JPA and JdbcTemplate transaction control --> 
    <property name="jpaVendorAdapter"> 
     <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> 
      <property name="showSql" value="false" /> 
     </bean> 
    </property> 
</bean> 

<!-- jdbc templates that are equals for all databases --> 
<bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate"> 
    <constructor-arg ref="dataSource" /> 
</bean> 
<bean class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate" id="simpleJdbcTemplate"> 
    <constructor-arg ref="dataSource" /> 
</bean> 
相關問題