如您所知,在spring applicationContext中,我们可以从persistence.xml定义entityManagerFactory bean,如下所示:
<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 :(得分: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>