Search code examples
javaspringspring-transactionstransactional

Spring transaction management over a datasource list


I have a Spring mvc rest webservice with a DataSourceManager bean that holds a map of datasource. Every customer has his own database and therefore his own datasource. The webservice loads the customer Datasource programmatically loading from DataSourceManager and if it does not exist it creates a new.

With this implementation is possible to use an annotation driven transaction management ? All the examples that I read have one or various datasources declared all on a config file.


Solution

  • Finally I solved my problem with this bean:

    @Bean
    @Scope(value=WebApplicationContext.SCOPE_REQUEST, proxyMode=ScopedProxyMode.TARGET_CLASS)
    public PlatformTransactionManager txManager(SessionInfo sessionInfo, DataSourceManager dsManager)   
    {               
        return dsManager.getTransactionManager(sessionInfo.getCustomerId()); 
    }
    

    Where SessionInfo is a session bean that holds the customer and DataSourceManager is a global bean that holds all the Datasources. Every web request load the correct Transaction Manager and the @Transactional annotation works with the corresponding datasource. It seems that works