deng hui
deng hui

Reputation: 1

can I get a jdbc datasource from jpa in spring application context?

as you know, in spring applicationContext we can define entityManagerFactory bean from persistence.xml just like:

    <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>

now if I want initialize the database as follow:

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

should I must config another data source bean for it? or I can ref to emf defined above ,or can ref to persistence.xml ?

Upvotes: 3

Views: 1802

Answers (1)

Ralph
Ralph

Reputation: 120761

 <!-- 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>

Upvotes: 1

Related Questions