How to set a specific DataSource for a Repository?

前端 未结 4 1141
半阙折子戏
半阙折子戏 2021-01-04 18:43

Is it possible to assign a specific DataSource to a @Repository?

I\'d like to create a test environment where in general I want to use the

相关标签:
4条回答
  • 2021-01-04 19:18

    The DataSource and JpaRepository are both tied to an EntityManager. You will have to segregate the repositories into separate packages for your requirement to work.

    Here is an example:

    <bean id="emf1" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="dataSource">
        <bean .../>
      </property>
      ...
    </bean>
    <jpa:repositories base-package="org.example.package1" entity-manager-factory-ref="emf1"/>
    
    <bean id="emf2" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="dataSource">
        <bean .../>
      </property>
      ...
    </bean>
    <jpa:repositories base-package="org.example.package2" entity-manager-factory-ref="emf2"/>
    
    0 讨论(0)
  • 2021-01-04 19:20

    well it depends on which is your design , cause there are different implementations that you can follow , f.e you can declare two beans for the two datasources and in your code specify to which one you want to hit , or else you could define two differents context and a shared context in which again you ll have to specify in your code which service you want to call. Here is an older question that might help you for the 1st approach

    0 讨论(0)
  • 2021-01-04 19:22

    @EnableJpaRepositories is the answer to your question. This should work with CrudRepository according to the informal documentations.

    Refer this detail tutorial on how to do this. I didn't put my effort to post the codes here as you may directly refer it much clearer in it.

    link to the Tutorial...

    0 讨论(0)
  • 2021-01-04 19:24

    Just set the name attribute of the @PersistenceContext annotation when declaring your EntityManager.

    @PersistenceContext(name="persistence-unit-name")
    private EntityManager em;
    
    0 讨论(0)
提交回复
热议问题