We use different DB schemas to implement multi-tenancy in an application. This has the advantage that the data for each client is stored in separate tables and permissions can be controlled at the database level. In our case, there is one schema for shared (master) data. There is another schema for client-specific data for each client, whereby the client schemas are all structured identically.
The entities for the master data are annotated with @Table in JPA, whereby the schema attribute is specified in each case: @Table(name=“…”, schema=”<master data schema>”)
For the entities for client-specific data, the schema attribute is not specified in the @Table annotation: @Table(name=“…”). Here, the default schema takes effect, which Hibernate then automatically places in front of the table names in the generated SQL statements. The default schema can be defined in persistence.xml:
<persistence-unit name=”…”>
…
<properties>
<property name=”hibernate.default_schema” value=”…”/>
…
</properties>
</persistence-unit>
A separate persistence unit with the corresponding default schema is defined for each client. In the application server, there is an associated entity manager for each persistence unit. When a client request is received, the server uses the user ID to determine which client the user belongs to and then uses the corresponding entity manager for database access.
Alternatively, you could manipulate the generated SQL statements afterwards and adjust the schema. Hibernate offers the option of registering an interceptor (org.hibernate.Interceptor) in persistence.xml, which is notified via corresponding callback methods before DB operations are executed:
<persistence-unit name=”…”>
…
<properties>
<property name=”hibernate.ejb.interceptor”
value=“<MyInterceptorClass>” />
…
</properties>
</persistence-unit>
In the onPrepareStatement(String) method, the SQL statement generated by Hibernate is passed as a parameter and can still be changed before execution, as the statement returned by the method is executed.
Conclusion: The first variant is certainly the more robust solution, while the interceptor solution gives you complete control over the DB statements issued by Hibernate.
Autor

Michael Buchholz
Jobs

Ihr Ansprechpartner
Gerne erzählen wir Ihnen mehr zu diesem Thema.



