Follow me on the "cloud" side (iv) build enterprise Multi-tenant applications using Eclipselink

Source: Internet
Author: User
Tags jboss

In the previous blog, we introduced the data isolation of multi-tenancy, the article introduces the implementation of Hibernate and Eclipselink for multi-tenancy, and at the end of the blog, I also explained the details of hibernate to realize multi-tenancy, this time, I want to bring you together. Use Eclipselink to build enterprise-class multi-tenancy projects.

Three implementations of Eclipselink

Since Eclipselink fully implements the JPA specification, we can use EJBS to build an enterprise-class multi-tenant project that first Eclipselink support the multi-tenant model in 3:
- single-table multi-tenancy, relying on the tenant area (Tenant discriminator columns) to isolate the rows of the table and implement a multi-tenant shared table.
- table-per-tenant multi-tenancy, relying on the table tenant Distinction (Table Tenant discriminator) to isolate the table, implement a tenant table, The shared database standalone schema pattern is broadly similar to the above.
- Virtual Private Database (VPD) multi-tenancy, which relies on Oracle VPD's own secure access policy (based on the dynamic SQL WHERE clause feature) to implement a multitenant shared table.

Table-per-tenant multi-tenancy Implementation
    • I think that's the second way, because it's more suitable for performance, separation, and flexibility.
    • First of all, the content of Persistence.xml, after the introduction of a blog, we should have configured the basic use of eclipselink environment.
Persistence.xml configuration:
<?xml version= "1.0" encoding= "UTF-8"?><persistence version="2.0"xmlns="http://java.sun.com/xml/ns/ Persistence " xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation ="Http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" >            <!--given persistence-unit name --    <persistence-unit name="Mt_hotel_service"transaction-type= "JTA">                <!--persistence with Eclipselink-        <provider>Org.eclipse.persistence.jpa.PersistenceProvider</provider>        <!--Using data sources configured in JBoss--        <jta-data-source>Java:jboss/datasources/jcmysqlds</jta-data-source>        <!--because the entity is configured to automatically scan here, no questions are listed in the system--        <properties>            <!--Modify the first load time problem--            < property name="Eclipselink.deploy-on-startup" value="True" / >            <!--run execute local SQL query --            < property name="Eclipselink.jdbc.allow-native-sql-queries"value= "true" />                            <!--Set the server type --            < property name="Eclipselink.target-server" value="JBoss " />            <!--logging level configuration --            < property name="Eclipselink.logging.level" value="FINE" />             <!--configuration static weave-in            < property name="eclipselink.weaving" value="Static" / >            <!--set a custom primary key generation strategy --            < property name= "eclipselink.session.customizer" value=" Com.tgb.itoo.base.util.uuid.UUIDSequence " />        </Properties>    </persistence-unit></Persistence>
    • The configuration of each row in the configuration is explained, and there is no more talking about it.
BaseEntity Configuration
    • For the configuration of the entity: the first is the entity inheritance used, the BaseEntity code is as follows:
 Packagecom.tgb.itoo.base.entity;ImportJava.util.Date;ImportJavax.persistence.Column;ImportJavax.persistence.EntityListeners;ImportJavax.persistence.GeneratedValue;ImportJavax.persistence.Id;ImportJavax.persistence.MappedSuperclass;ImportJavax.persistence.Temporal;ImportJavax.persistence.TemporalType;ImportJavax.persistence.Transient;@MappedSuperclass@EntityListeners(value = {Entitylistener.class}) Public Abstract  class baseentity implements IdEntity {    Private Static Final LongSerialversionuid =1L Public baseentity() {Super(); }@Id    @GeneratedValue(Generator ="System-uuid")//Custom UUID generation policy    @Column(name ="id")protectedString ID; PublicStringgetId() {returnId } Public void setId(String ID) { This. id = ID; }/** * Database name * /    @Transient //Do not persist    PrivateString DataBaseName; PublicStringGetDatabaseName() {returnDataBaseName; } Public void Setdatabasename(String dataBaseName) { This. dataBaseName = DataBaseName; }/** * Remarks * * *    @Column(name ="comment", length =255)PrivateString comment;/** * operator * *    @Column(name ="operator", length = -)PrivateString operator; ......}
    • The public properties of an entity are defined in BaseEntity, which focuses on two property values
      1. ID: ID uses a custom UUID generation strategy, which is described in the next blog post.
      2. dataBasename: From the name is very clear is the database name, but this property is not used to persist, so use the @transient annotation, this property is mainly to pass the parameters, will be in the implementation of multi-tenancy, Because each operation of any entity should be determined to be the operation of that tenant, it is necessary to make the data crud correspond to its own database.
The design of a specific entity
 Packagecom.tgb.itoo.authority.entity;ImportJavax.persistence.Column;Importjavax.persistence.Entity;Importjavax.persistence.Table;ImportOrg.eclipse.persistence.annotations.Multitenant;ImportOrg.eclipse.persistence.annotations.MultitenantType;ImportOrg.eclipse.persistence.annotations.TenantTableDiscriminator;ImportOrg.eclipse.persistence.annotations.TenantTableDiscriminatorType;Importcom.tgb.itoo.base.entity.TimeBaseEntity;/** * Role entity * @author Hanyi * */@Entity@Table(name="Ta_role")@Multitenant(value=multitenanttype.table_per_tenant)@TenantTableDiscriminator(Type=tenanttablediscriminatortype.schema, contextproperty="tenant_id") Public  class Role extends timebaseentity {    Private Static Final LongSerialversionuid =598970641717338526L/** * Role name * /    @Column(name ="RoleName", length = +)PrivateString RoleName;/** * Character description * /    @Column(name ="Roledescribe", length = -)PrivateString Roledescribe; ......}
    • Attention should be paid to the multi-tenancy annotations in the entity, where multitenanttype.table_per_tenant is used to differentiate between using a table-dependent tenant, and there are three types of tenanttablediscriminatortype. The schema is used here, that is, each tenant uses a separate schema that defines the contextproperty= "tenant_id", which sets the Entitymanager to differentiate between tenants based on the tenant_id attribute.
Injection of Entitymanager
    //实体管理器,管理实体持久化操作,通过容器注入    @PersistenceContext"MT_HOTEL_SERVICE")    protected EntityManager em;
Set up multi-tenancy properties
/** * 根据数据库名字,得到当前操作对应的实体管理器的名字 * @return 实体管理器 */protected EntityManager getEntityManager() {            //dataBaseName的值,给实体管理器赋值,此处的tenant_id是在实体注解时规定,只要统一可以是任何值。    if (dataBaseName!=null && !dataBaseName.equals(""))     {        em.setProperty("tenant_id", dataBaseName);    }    //如果dataBaseName的值为空,那么就选择一个默认的库,这里选择的是根库(base)    else     {        em.setProperty("tenant_id""base);    }    return this.em;}
The specific EaO method
/**     * @author hanyi     * @MethodName : save     * @Description : 无返回值的泛型保存方法     * @param t:要保存的实体     */    public  voidsave(Object entity) {        //从实体类型中拿到当前操作的数据库名字        getDataBaseName(entity);        //取得实体管理器,进行持久化操作        getEntityManager().persist(entity);         }
    • This ignores the code from the GetDatabaseName (entity) method, and its main function is to use reflection to get the value of the DatabaseName set by the foreground and then Getentitymanager.
Complete the configuration

The data-tier isolation of this ECLIPSELINK+EJB+JPA implementation of enterprise-class multitenant applications is also resolved.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Follow me on the cloud side (iv) build an enterprise multi-tenant application using Eclipselink

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.