sunitk / multitenancy-dynamic-tenant

Spring Boot 2 JPA Hibernate with database per tenant with dynamic configuration of tenants, secured by Spring Security
Apache License 2.0
99 stars 76 forks source link

@Transactional in Service classes doesn't work #7

Closed cdekker closed 3 years ago

cdekker commented 5 years ago

I am having issues with creating atomic operations in my Service classes. In my case I have a service that interacts with 2 repositories (both in the same tenant package) that I would like to wrap in a single transaction. If I add @Transactional to any of my methods there, Spring throws the following error:

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.transaction.PlatformTransactionManager' available: expected single matching bean but found 2: applicationTransactionManager,tenantTransactionManager

All my individual calls on the Repositories work fine, because they are bound to the correct Hibernate configuration:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "tenantEntityManagerFactory",
        basePackages = { HibernateConstants.PACKAGE_REPOSITORY_TENANT },
        transactionManagerRef = "tenantTransactionManager")
public class HibernateTenantConfig extends HibernateConfig {
...
}

It looks like Spring does not know which Transaction Manager to select in my Service classes, even though they are logically bound to either the tenant packages or application packages (you call them 'master').

How can I solve this? Preferably in a way where I don't have to explicitly mention the Transaction Manager on every single @Transactional annotation.

Jam3si commented 4 years ago

Just add: @Service @Scope(proxyMode = ScopedProxyMode.INTERFACES) @Transactional(transactionManager = "tenantTransactionManager")

To your *ServiceImpl

sunitk commented 3 years ago

Looks like this is resolved. Thanks @Jam3si