Multitenant

Multitenancy allows multipe tenants to share tables using a discriminator column. Tenant discriminator columns are not entity attributes, but they will be automatically added in SQL query.

If a mapped superclass or entity class is configured as multitenant in META-INF/persistence.xml or orm.xml, its subclass entities will inherit the configuration as multitenant entities unless they are overridden. For example, class hierarcy:

               PersistenceBaseType
          ------------------------------------------
           |          |          |                 |
         User        Role      Permission       Employee
                                                /      \
                                    FullTimeEmployee  PartTimeEmployee
orm.xml
<mapped-superclass class="com.example.PersistenceBaseType">
	<multitenant>
		<discriminator-column name="tenant_id" type="java.lang.Long" 
			value-mapping-property="tenant.id"/>
	</multitenant>
</mapped-superclass>

<entity class="com.example.Permission">
	<multitenant>
		<discriminator-column name="permission_group" type="java.lang.String" 
			length="30" value-mapping-property="permission.group"/>
	</multitenant>
</entity>

<entity class="com.example.User">
	<multitenant enabled="false"/>
</entity>

The class hierarchy is configured as multitent except the User entity. Permission entity uses a different multitenant discrimininator column than other entities of the class hierarchy.

discriminator-column element specifies tenant discriminator column name, type, length and value mapping property whose value must be specified in entity manager. Discriminator column type should be number or string type such as java.lang.Long and java.lang.String. The length attribute is applicable to string type for schema generation.

For example,

EntityManager em = ...
em.setProperty("instance.id", 100);
em.setProperty("permission.group", "group1");
An entity manager for one tenant must not be reused for a different tenant because

Primary Key

If an entity is multitenant enabled, but it does not have auto id generator, its identifier may not be unique among all tenants. So its tenant discriminator column must be a primary key column. Tenant discriminator column must be in all unique keys of primary and secondary tables.

Caching

If an entity is multitenant enabled, but it does not have auto id generator, the entity will not be cached in 2nd-level cache since its identifier may not be unique among all tenants.