Hibernate using multiple databases

后端 未结 9 2093
死守一世寂寞
死守一世寂寞 2020-12-05 05:25

Someone know how to add a another datasource in hibernate configuration and how to configure Spring to that datasource its autoinject in my respective DAO?

This is m

9条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 06:18

    I'll add my example too. Maybe it will be usefull for another situations like getting data from one database and writing it to another with EntityManager.

    So my applicationContext.xml:

    
    
    
    
    
    
      
    
    
    
      
      
      
    
    
    
      
      
      
      
    
    
    
    
    
    
      
    
    
    
      
      
      
    
    
    
      
      
      
      
    
    

    Package business.domain has entity classes for remote connection.

    Package local.business.domain has entities for local connection.

    Entities have annotation mappings for columns and relations.

    Then 2 DAO classes:

    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import org.springframework.stereotype.Repository;
    import org.springframework.transaction.annotation.Transactional;
    
    @Repository
    public class RemoteDao {
    
      @PersistenceContext(unitName="unitRemote")
      protected EntityManager em;
    
      // ...
    
    }
    

    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import org.springframework.stereotype.Repository;
    import org.springframework.transaction.annotation.Transactional;
    
    @Repository
    @Transactional(value="transactionManagerLocal")
    public class LocalDao {
    
      @PersistenceContext(unitName="unitLocal")
      protected EntityManager em;
    
      // ...
    
    }
    

    With this I could use @Autowired to inject DAOs in my JUnit test:

    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "/config/applicationContext.xml" })
    public class DaoTest {
    
      @Autowired
      private RemoteDao remoteDao;
    
      @Autowired
      private LocalDao localDao;
    
    
      @Test
      public void daoTest(){
        Entity entity = remoteDao.find(id);
        localDao.persist(entity);
      }
    
    }
    

    So here it's possible to use DAOs without service if this is needed for simple applications, tests or DB migration scripts.

提交回复
热议问题