-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Description
I hope this is also the right place to ask about this, I know that some things should go under spring-data-commons, I don't mind this being moved of course
I'm using spring-data-jpa
, in a column discriminator based multi-tenant environment (so all of our @Entity
s have @TenantId
). For some tests (relying on @DataJpaTest
, we would like to switch which tenant is the current one, so I have something like this:
@TestComponent
@Primary
class TestTenantIdentifierResolver : CurrentTenantIdentifierResolver<String>, HibernatePropertiesCustomizer {
var currentTenant: String? = null
override fun resolveCurrentTenantIdentifier(): String {
return currentTenant
}
override fun validateExistingCurrentSessions(): Boolean {
return true
}
override fun isRoot(tenantId: String): Boolean {
return tenantId == "my-root-tenant"
}
override fun customize(hibernateProperties: MutableMap<String, Any>) {
hibernateProperties[AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER] = this
}
}
This initially didn't work, as @Autowired testTenantIdentifierResolver
and calling currentTenant = "a tenant"
did nothing, the tenant hasn't actually changed in the rest of the test method.
I went back to the original how-to guide about this, and noticed that I was missing @TestExecutionListeners(listeners = [DependencyInjectionTestExecutionListener::class])
on top of my test class.
When I added this annotation, changing the tenant worked as expected, and tests were successful.
But it did have a bad side effect, all of the tests that were lazily fetching collections started to fail with could not initialize proxy - no Session
, and no matter what I did they kept failing. Only removing the @TestExecutionListeners
annotation made it possible for collections to be lazily fetched again
Is there a way to configure a @DataJpaTest
that could support both tenant resolution and still support lazy loading collections?
reproduced example here https://github.com/ofir-popowski/tenant-resolver-issue