Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multitenant - Discriminator - @CurrentTenant not honored if session created by SessionFactory.currentSession #781

Closed
jdaugherty opened this issue Nov 4, 2023 · 4 comments

Comments

@jdaugherty
Copy link
Contributor

Description:
If a hibernate session has not yet been used for the current thread, and sessionFactory.currentSession is invoked, the tenant will not be honored. If Author.withSession { Session session -> } is invoked first, then sessionFactory.currentSession will honor the tenant.

Affected Versions
My issue was originally found in a Grails 5.x project, but given that Grails 6.x has been released, I reproduce it in Grails 6.x as well.

Sample project:
Generated a Grails 6 project, setup discriminator based multitenant config, added an Author domain class, create two Authors with opposite tenants in BootStrap, added service demonstrating the problem, and added a test case for service.

https://github.com/jdaugherty/multitenant-issue

Run the integration tests to reproduce:
gradle integrationTest

@Goliath
Copy link

Goliath commented Nov 4, 2023

@jdaugherty IMO that's correct behavior, as sessionFactory.currentSession is returning non tenant, default sessionFactory.
If I correctly remember you should use sth like:

sessionFactory = hibernateDatastore.getDatastoreForConnection(Tenants.currentId()).getSessionFactory()

hope that helps.

@jdaugherty
Copy link
Contributor Author

jdaugherty commented Nov 4, 2023

Thank you @Goliath. This behavior is frustrating:

  • If the session is already initialized, sessionFactory returns a session that works as expected.
  • A Grails plugin / library that uses hibernate can unexpectedly expose this behavior.
  • Grails is built upon Spring Boot so existing code that is written for Spring usually works. In this case, non-Grails code could create a session and thus silently fail.

Hibernate documents how to create custom sessions. The GORM guide mentions the HibernateConnectionSourceFactory as how it creates a SessionFactory which implies that sessionFactory should work. This defect should at least be documented in the guide or be fixed to be consistent in Grails & non-Grails code.

@Goliath
Copy link

Goliath commented Nov 6, 2023

For completeness here are GORM docs describing above:
https://gorm.grails.org/latest/hibernate/manual/index.html#_multi_tenancy_and_the_session_factory

@jdaugherty
Copy link
Contributor Author

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants