Multiple database with Spring+Hibernate+JPA

后端 未结 6 1529
别跟我提以往
别跟我提以往 2020-12-04 13:43

I\'m trying to configure Spring+Hibernate+JPA for work with two databases (MySQL and MSSQL).

My datasource-context.xml:



        
6条回答
  •  旧巷少年郎
    2020-12-04 14:10

    If you follow this tutorial, http://www.javacodegeeks.com/2010/05/jboss-42x-spring-3-jpa-hibernate.html you can make the following changes to access two different databases:

    1. persistence.xml, define a second pesristence-unit for your second database.
    2. spring.xml, define a second entityManagerFactory bean under a different name, lets say "entityManagerFactoryDB2" and configure it to use the persistent unit for the second database.
    3. for every DAO you want to access the second database include the following :

      @Autowired
      private EntityManagerFactory entityManagerFactoryDB2;
      
      @PostConstruct
      public void init() {
          super.setEntityManagerFactory(entityManagerFactoryDB2);
      }
      

    Thats all!

    On spring service classes, use the DAOs as usual!

提交回复
热议问题