使用Spring Java @Configuration定义多个entityManagerFactory bean

时间:2014-02-25 12:48:10

标签: spring entitymanager spring-data-jpa jta spring-java-config

我在我的系统中使用多个数据库。我正在使用AtomikosDataSourceBean在多个dbs中启用xa分布式事务。

spring-configuration.xml文件中,我可以为两个单独的EntityManagerFactory创建bean,比如说entityManagerFactory1和entityManagerFactory2。但是当我使用Spring Java @Configuration时,我会收到错误。

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' is defined

如果我创建一个为entityManagerFactory而另一个创建为entityManagerFactory1,那么我会收到错误

Caused by: java.lang.IllegalArgumentException: Not an managed type: class com.tom.boon.core.model.Person

在entityManagerFactory1下创建的Enitities。

有人可以帮我弄清楚如何在Spring Java @Configuration中定义两个separte entityManagerFactory。

2 个答案:

答案 0 :(得分:0)

您并未提供有关配置的详细信息。假设它们应该是相当简单的,那么你定义了两个bean:entityManagerFactory1和entityManagerFactory2

第一次使用时,您需要通过@Resource引用这些内容:

@Resource(name =  "entityManagerFactory1")
EntityManager entityManager

以及其他用法:

@Resource(name =  "entityManagerFactory2")
EntityManager entityManager

这应该有效,除非出现其他问题。如果是这种情况,请提供有关您正在做的事情的更多详细信息。希望这会有所帮助。

答案 1 :(得分:0)

在您的配置文件中,如下使用persistenceUnitName属性:

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

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

了解dataSource与它们之间的区别。您可以在dataSourceFoodataSourceBar中定义不同的连接属性。然后只需使用:

@PersistenceContext(unitName = "foo")
private EntityManager foo;

@PersistenceContext(unitName = "bar")
private EntityManager bar;

和EntityManagers的foo和bar应该连接到不同的数据库。

不要忘记,如果您想让Spring识别<context:annotation-config />注释,则需要在配置文件中使用@PersistenceContext元素。