Multiple SessionFactories, multiple DataSources and Hibernate TransactionManager can take only one Sessionfactory
I have @Transactional annotation in all my DAOs, but I can only define one TransactionManager that takes only one SessionFactory. I have one SessionFactory per customer, one DataSource per customer and apparently I need to change TransactionManager for every customer. But how can I get correct transacti开发者_StackOverflow中文版on manager for customer, when I can only define one Spring bean name for one TransactionManager?
Spring 3 has support for multiple transaction managers, while keeping the declarative @Transactional delimitation
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/transaction.html#tx-multiple-tx-mgrs-with-attransactional
Is this not what you want?
This is an example of where Spring's declarative transaction management is no longer convenient, and you need to switch to programmatic management in order to get the flexibility that you need. This will allow you to inject, for example, a map of transaction managers into your DAO layer, and select the correct one accordingly, using TransactionTemplate
to make things easier.
Alternatively, if you're running inside a container that support JTA, then you can use Spring's JtaTransactionManager
. This delegates transaction management to the app server, while retaining the Spring API semantics. It also means that an arbitrary number of DataSources and SessionFactories can participate under one transaction manager. However, this means that your DataSources need to be fully managed by the appserver, which is probably not going to work for you.
You can create a PlatformTransactionManager
that will delegate calls to a customer-specific transaction manager for the current customer. Current custormer can be stored, for example, as a ThreadLocal
variable.
精彩评论