Reputation: 6532
I have a multitennanted application running in Jboss 5. Currently this is not making use of hibernate, but I'm attempting to upgrade it to do so. All is fine except the application determines which datasource to use based on a subdomain in the URL that is requested. e.g. a request to company1.myapp.com/resource/id/1
will request a connection from JNDI for DSN java:/datasources/company1
and a request to company2.myapp.com/resource/id/1
will request a connection from JNDI for DSN java:/datasources/company2
each one connecting to its own database to prevent any possible data leakage.
I'd like to do a similar thing with hibernate under Jboss 8 (Wildfly). Unfortunately because Wildfly is managing my HibernatePersistenceProvider
(I just inject my EntityManager, and let Wildfly do all the work) I can't tell it programatically which DSN to use for its connections.
Is there a sensible way to do this that I've missed? I've tried to change the provider to be a custom class which extents HibernatePersistenceProvider
, except I just end up with an error that it can't find my class. And I'm not even convinced this will work anyway as I can't get hold of the request in this class very easily...
Basically I need to determine the DSN from the URL and use it to tell Hibernate which datasource to use for each request.
Any ideas?
Upvotes: 1
Views: 585
Reputation: 4573
Yes my idea is to achieve this you will need to maintain hibernate configuration files according to your subdomain. Like,
for
company1.myapp.com
suppose we have hibernate config file ascompany1_Hibenate.cfg.xml
and
for
company2.myapp.com
suppose we have hibernate config file ascompany2_Hibenate.cfg.xml
After this at the of context loading you will build sessionFactories
For example :
SessionFactory sessionFactory1 = new Configuration().configure("company1_Hibenate.cfg.xml").buildSessionFactory();
SessionFactory sessionFactory2 = new Configuration().configure("company2_Hibenate.cfg.xml").buildSessionFactory();
And now in interceptor you will check domain and accordingly use sessionFactory.
Upvotes: 1
Reputation: 1846
you could specify different persistence units in your persistence.xml, one for each subdomain. Then you could use a cdi provider method to inject the appropriate EntityManager depending on the domain that has been queried. But if the number of subdomains isn't fixed in your setup this solution won't work.
Upvotes: 0