Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

EclipseLink/Development/Indigo/Multi-Tenancy

< EclipseLink‎ | Development‎ | Indigo
Revision as of 16:15, 28 February 2011 by Douglas.clarke.oracle.com (Talk | contribs) (Example)

Enhancement request: bug 337323

Multi-Tenancy

The goal of this feature is to allow multiple application tenants to share the same schema using tenant identifying column(s).

Requirements

  1. Support configuration of shared multi-tenant entity types using EclipseLink specific annotations and/or eclispelink-orm.xml with the XML overriding the annotation.
    • Augment database queries to limit query results to the tenant identifier values provided as property values
    • Ensure all INSERT, UPDATE, DELETE operations populate and limit their effect to the defined tenant identifiers
  2. Support accessing shared data at either the EntityManagerFactory or EntityManager
    • When using EMF the underlying cache must be unique to the provided tenant identifiers
  3. Support the tenant identifier columns being:
    • un-mapped
    • mapped
    • part of the identifier of the entity (mapped)
  4. Support schema generation including the specified tenant identifier column(s). Default type will be based on any mapping if available otherwise it will be assumed to be a string and override with the column's definition

Configuration

With this new feature developers will be able to enable shared tenant table(s) usage at the entity level using one or more columns associated with persistence unit or context property values that must be provided.


The following new EclipseLink metadata will be added.

Annotation

@Target({TYPE}) 
@Retention(RUNTIME)
public @interface TenantShared {
  /**
   * (Required) At least one tenant id must be specified when using a tenant shared strategy.
   */
  TenantId[] values();
}

@Target({}) 
@Retention(RUNTIME)
public @interface TenantId {
  /**
   * (Required) The name of the context property to apply to the 
   * tenant id column.
   */
  String property();

  /**
   * (Optional) Defines the column that will be mapped for this tenant id.
   * The column name will default to the required property name.
   */
  Column column() default @Column;
}


Eclipselink-orm.xml

<xsd:complexType name="tenant-shared">
  <xsd:annotation>
    <xsd:documentation>

    ...

    </xsd:documentation>
  </xsd:annotation>
  <xsd:sequence>
    <xsd:element name="tenant-id" type="orm:tenant-id" minOccurs="1" maxOccurs="unbounded"/>    
  </xsd:sequence>
</xsd:complexType>

<xsd:complexType name="tenant-id">
  <xsd:annotation>
    <xsd:documentation>

      ...

    </xsd:documentation>
  </xsd:annotation>
  <xsd:sequence>
    <xsd:element name="column" type="orm:column" minOccurs="0"/>    
  </xsd:sequence>
  <xsd:attribute name="property" type="xsd:string"/>    
</xsd:complexType>
Example
<entity class="model.Employee">
    <table name="EMPLOYEE" />
    <tenant-shared>
        <tenant-id property="eclipselink.tenant.id"><column name="TENANT_ID"/></tenant-id>
    </tenant-shared>

Metadata Defaults and processing

The new metadata will available at the Entity and MappedSuperclass levels. When specified at the MappedSuperclass level, the tenant metadata will apply to all sub-entities of that class unless they specify their own tenant metadata.

Within an inheritance hierarchy, tenant metadata can only be applied at the root level of the inheritance hierarchy. An exception will be thrown otherwise.

The column name if unspecified will be the property name converted into a column name using standard JPA String -> column name translations.

Within XML, it is possible to specify a default tenant metadata through the persistence unit metadata defaults.

<xsd:complexType name="persistence-unit-defaults">
  ...
    <xsd:sequence>
     ...
       <xsd:element name="tenant-shared" type="orm:tenant-shared" minOccurs="0"/>
     ...
    </xsd:sequence>
</xsd:complexType>

When this default value is specified, it will be applied to all entities of the persistence unit minus those that specify their own tenant metadata. Alternatively, users may specify tenant metadata at the entity-mappings level as well which would override a persistence unit default and apply itself to all entities of the given mapping file (unless they individual entities have specified their own metadata). This follows similar JPA XML metadata overriding rules.

<xsd:element name="entity-mappings">
  ...
    <xsd:sequence>
     ...
       <xsd:element name="tenant-shared" type="orm:tenant-shared" minOccurs="0"/>
     ...
    </xsd:sequence>
</xsd:complexType>

Any entity not marked with tenant metadata and with no persistence unit default will be remain visible to all tenants.

The tenant id column(s) are assumed to exist on the primary table. If using secondary tables the column metadata must specify the table if it is not on the primary.

Tenant id columns are not expected for the following tables (which refer back to their related entity through a primary key association):

  1. @CollectionTable
  2. @JoinTable

NOTE: This assumes id generation is shared across persistence units. Otherwise, in a multi-tenant environment, the tenant id becomes part of the primary key and all tables must then have a tenant id (which becomes another join column on the relation tables).

When using DDL generation, the user need not worry about this. The DDL generation framework will be responsible for ensuring all necessary tables have a tenant id column.

Mapped tenant id columns

When using mapped tenant id columns, two scenarios need to be discussed:

Part of the entity identifier

When writing, the tenant id can be populated by the user, if it is not, its value should be populated from its associated property. Querying based on primary key will require us to filter the redundancy of adding the tenant column to the SQL statement multiple times. When querying outside of the primary key, the tenant column portion of the identifier must be included.

Not part of the entity identifier

Always appended to any read and write query when the mapped tenant id is not populated directly by the user.

Exceptions

EclipseLink validation exceptions will be thrown in the following cases:

  • When tenant metadata is applied to subclasses of an entity hierarchy.
  • At run time when a tenant property can not be found.

Property configuration

At runtime the properties can be specified via a persistence unit definition or passed to a create entity manager factory call. The value of these tenant is properties will be used to create unique session names ensuring separate sessions are provided for each tenant. For this to happen tenant id properties should be qualified with "eclipselink.tenant". The value of all these tenant id properties will then be sorted and concatenated together.

The properties may be included within a peristence unit definition in the persistence.xml file.

<persistence-unit name="multi-tenant">
  ...
  <properties>
    <property name="eclipselink.tenant.id" value="707"/>
    ...
  </properties>
</persistence-unit>

Or alternatively (and most likely preferred) in code as follows:

HashMap properties = new HashMap();
properties.put("eclipselink.tenant.id", "707");
...     
EntityManager em = Persistence.createEntityManagerFactory("multi-tenant", properties).createEntityManager();

Core

The tenant id column(s) (multiple if using secondary tables) will be initialized during the pre-initialization of each descriptor of the persistence unit.

Those columns will then be applied in two places.

  1. We will leverage the current additional join expression from the DescriptorQueryManager to filter tenants. This is similar to the Additional Criteria feature. During postInitialization of the descriptor query manager after we had appended the additional criteria (if there is some), we will append the tenant id column(s) and its value(s) to the additional join expression.
  2. For inserts, we will append the tenant id column(s) and value(s) when building the row representation of an object. This is done in the following methods from ObjectBuilder (Note: this is similar to the handling of the discriminiator column within an inheritance hierarchy)
    1. buildRow
    2. buildRowForShallowInsert
    3. buildRowForUpdate
    4. buildRowWithChangeSet
    5. buildTemplateInsertRow

Querying

The tenant id column and value will be supported through the following entity manager operations:

  • persist
  • find
  • refresh

And the following queries:

  • named queries

NOTE: EclipseLink will not modify, therefore, support multi-tenancy through named native queries. When using these types of queries within a multi-tenant environment, the user will need to be aware and handle any multi-tenancy issues themselves directly in their native query. To all intent and purpose, named native queries should be avoided in a multi-tenant environment.

Support for update all and delete all queries should be included.

DDL generation

DDL generation will need to support the generation of tenant id columns. The DDL generation of columns is based off the descriptor's columns. During pre-initialization we therefore need to ensure that our tenant id columns are built and added to this list. This should be done after the descriptor table initialization (including inheritance hierarchies) has been preformed. Mapped tenant id columns are added automatically and we should avoid adding them more than once.

if (session.hasTenantId()) {
  for (DatabaseTable table : getTables()) {
    DatabaseField tenantIdField = session.getTenantIdField();
    tenantIdField.setTable(table);
    getFields().add(buildField(tenantIdField));    
  } 
}

Open Issues

  1. How can an admin user access data from multiple tenants?

Back to the top