I have different classes that extends CrudRepository<T, T> of Spring Data JPA Framework. It implicit uses the global EntityManager bean.

Now I want to create a service that should connect to a different database. Which means I'd have to somehow inject a different em/datasource. But how can I bind a database explicit to spring beans / services?

有帮助吗?

解决方案

There are multiple ways of doing it. What we did in one of our project is to define two different packages each for different datasource and defined different beans for them like this:

<beans>
    <jpa:repositories base-package="com.abc.repository" transaction-manager-ref="abcTransactionManager" entity-manager-factory-ref="abcEntityManagerFactory"/>

    <jpa:repositories base-package="com.def.repository" transaction-manager-ref="defTransactionManager" entity-manager-factory-ref="defEntityManagerFactory"/>

  <bean id="abcTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="abcEntityManagerFactory"/>
    <qualifier value="abcTransactionManager"></qualifier>
  </bean>

  <bean id="defTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="defEntityManagerFactory"/>
    <qualifier value="defTransactionManager"/>
  </bean>
</beans>

Similarly defining corresponding entity manager factory. In this way, whatever repositories are defined in package abc will use abcEntityManager and similarly for def.

The other way I have seen it working is applying transaction with appropriate entity manager like this:

 @Transactional("abcTransactionManager")
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top