Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable multi-tenancy in Hibernate 4 with JPA?

It looks to me as though support for multi tenancy has been added to hibernate for nearly six months now and updated at least once since.

It looks fairly trivial to obtain a multi-tenant Session outside of JPA:

Session session = sessionFactory.withOptions().tenantIdentifier( "jboss" ).openSession();

But how would you enable it in an application that uses hibernate via JPA? (If possible).

Thanks in advance.

like image 211
rich Avatar asked Aug 31 '11 09:08

rich


2 Answers

You can configure it via properties in persistence.xml as follows:

<property name="hibernate.multiTenancy" value="DATABASE"/>
<property name="hibernate.multi_tenant_connection_provider" value="com.example.MyConnectionProvider" />
<property name="hibernate.tenant_identifier_resolver" value="com.example.MyTenantIdResolver" />

If you use SCHEMA as multi-tenancy strategy hibernate.multi_tenant_connection_provider is not needed.

You can also set these properties in your code and pass them in a map to Persistence.createEntityManagerFactory(). In this case you can pass an object instance, not just a class name.

More info in Hibernate documentation.

like image 167
kkamenev Avatar answered Oct 17 '22 09:10

kkamenev


EntityManager.getDelegate() will return underlying SessionImpl.

like image 38
bpgergo Avatar answered Oct 17 '22 11:10

bpgergo