Hibernate using multiple databases

后端 未结 9 2090
死守一世寂寞
死守一世寂寞 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 05:56

    I assume you have a set of DAOs that should use dataSource1 and appropriate sessionFactory1, while others should use different dataSouce2 and sessionFactory2 based on dataSource2. Of course you need to declare your second dataSource and other beans: simply copy the configuration you already have and change bean ids so they won't collide. Everything should be mirrored except :

    
        
    
    
    
        
        
    
    
    
        
        
    
    
    
    
        
    
    
    
        
        
    
    
    
        
        
    
    
    
    

    And here comes the real problem: you now have two transaction managers bound to different session factories, which in turns are routed to different data sources. But @Transactional annotations will always use only one transaction manager - the one named transactionManager by default (note I explicitly pointed transactionManager1. This means that DAOs using second data source will participate in transactions started within first data source - this is obviously not what intended.

    There are some workaround to this, like explicitly defining transaction manager name in @Transactional annotation (never tried it) or using TransactionTemplate, but as you can see problem should be well thought.

    As for autowiring - if you autowire by name, name your fields the same as session factories or data sources ids and it should work - but is your smallest problem actually.

提交回复
热议问题