网络科技

    今日:526| 主题:278655
收藏本版
互联网、科技极客的综合动态。

[其他] Multi-Tenancy Using JPA, Spring, and Hibernate (Part 1)

[复制链接]
马上有钱 投递于 2016-12-1 12:58:45
182 1
Multi-tenancy allows an application to behave as multiple independent applications hosted for different clients (i.e. organizations). This might not sound impressive, however as the number of clients increase it becomes more evident that it is easier and more cost effective to run a single application hosted for all the clients rather than hosting an independent application for each client.
  Multi-tenancy has become more popular lately and is very useful for the economy in software companies since it makes your service more affordable using cheaper installations/costs. This is because multi-tenancy can lead your business to a higher level of competitive differentiation.
  How Does Multi-Tenancy Work?

   Multi-tenancy allows a single application instance to be served for multiple tenants on a single hosting server. This is usually performed by either separating databases ,  separating schemas , or  sharing schemas .
  This architecture therefore allows for a single instance to service different companies.
   

Multi-Tenancy Using JPA, Spring, and Hibernate (Part 1)

Multi-Tenancy Using JPA, Spring, and Hibernate (Part 1)-1-网络科技-impressive,affordable,performed,different,companies

  Multi-tenancy works by using the concept of tenants, each tenant has access only to his corresponding data, even if they are in the same or different database. It means that you can have multiple tenants (usually one per client) who will use your application as if it were a single application. Amazing, isn’t it?
  Multi-Tenancy Implementation: Software Architecture

  Let’s start with the basic, multi-tenancy has tgree different ways to implement:
  
       
  • Separate databases : Each tenant has its own database.   
  • Separate schemas : Tenants share common database but each tenant has its own set of tables (schema).   
  • Shared schema : Tenants share common schema and are distinguished by a tenant discriminator column.  
  No choice is better than another, every choice has different advantages and disadvantages, therefore it all boils down to what you want to compromise:
  
       
  • Quantity of tenants   
  • Performance   
  • Time of development   
  • Reliability   
  • Disaster recovery   
  • And so on…  
  When you want to achieve a feature, it usually brings down another.
  For instance: Separate-database is fully isolated, also it provides backup easily per tenant, however its performance isn’t so good as shared schema when there are a lot of clients.
   For more comprehensive details about Multi-tenant architecture I suggest the following MSDN article which delves more into the topic.
  Multi-tenancy implementation

  Hibernate, Spring, JPA

   In this section we are going to use the Java specification for accessing POJOs to relational databases, that is the Java Persistent API ( JPA ).
   As discussed earlier in the blog post, there are different approaches to implement Multi Tenancy, in this example we are going to use a separate database per tenant. In order to access the database we are going to use Hibernate which is a JPA Implementation.
   We have chosen Hibernate because it is a well known ORM which has provided support for multi-tenancy implementation since version 4.  To use Hibernate with your Java application all you need to do is to implement two interfaces: MultitenantConnectionProvider and  CurrentTenantIdentifierResolver .
   Your custom implementation of these classes will mainly differ based on your chosen multi-tenancy implementation architecture as described in the previous sections. However, it should be noted that Hibernate does not yet support the shared schema architecture (see HHH-6054 ).
  Hibernate Sessions

  Through the use of these sessions Hibernate is able to create transactions on entities. A session is opened and closed per transaction, when the session is created the tenantId is specified. Through the use of the tenantId, Hibernate can determine which resources to use, such that a tenant would access its (and only its) database.
  In order to be able to create sessions, the SessionFactory class can be used. The SessionFactory needs to be provided with the tenantId so it is able to create a session appropriate to the database/schema that would be used by the tenant of the session being created. Below is an example of how a session is created:
  1. Session session = sessionFactory
  2.         .withOptions()
  3.         .tenantIdentifier(yourTenantIdentifier)
  4.         ...
  5.         .openSession();
复制代码
  Note:Since we use JPA, we don’t have to use the above code because Hibernate sessions are created automatically by JPA.
   Note:Also, don’t confuse Hibernate sessions with Http sessions, one is for database transactions, the other is for a user across more than one page request.
  Implementation Details

  MultitenantConnectionProvider and CurrentTenantIdentifierResolver

  So now that we know how Hibernate works for multi-tenancy, some more questions can arise.
  How does Hibernate know what database or schema to choose in multi-tenancy?

   This is done through our custom implementation of MultitenantConnectionProvider . Our implementation provides a different connection by  tenantId . This connection is then used for the Hibernate  session .
  How does Hibernate know which tenant to use?

   For that we must implement CurrentTenantIdentifierResolver , this class has a method called resolveCurrentTenantIdentifier() that resolves the issue of which tenantId must be used by hibernate when a session is created.
   Let’s implement MultitenantConnectionProvider. We have the interface class MultitenantConnectionProvider which has the next implemented classes by hibernate:
  
       
  • AbstractDataSourceBasedMultiTenantConnectionProviderImpl   
  • AbstractMultiTenantConnectionProvider   
  • DataSourceBasedMultiTenantConnectionProviderImpl  
   For our purpose, we want to provide connections to different databases through several DataSources. For that we could use a map<TenantId, DataSource> , in this way we’d get the  DataSource by the  tenantId . Also, we could extend  DataSourceBasedMultiTenantConnectionProviderImpl but it uses jndi. As we will not use jndi in this post, we implement  AbstractMultiTenantConnectionProvider instead:
  1. /**
  2. * It gets the connection based on different datasources.
  3. */
  4. public class MultiTenantConnectionProviderImpl extends AbstractDataSourceBasedMultiTenantConnectionProviderImpl
  5. {
  6.     Log logger = LogFactory.getLog(getClass());
  7.     private static final long serialVersionUID = 14535345L;
  8.     @Autowired
  9.     private DataSource defaultDataSource;
  10.     @Autowired
  11.     private DataSourceLookup dataSourceLookup;
  12.     /**
  13.      * Select datasources in situations where not tenantId is used (e.g. startup processing).
  14.     */
  15.     @Override
  16.     protected DataSource selectAnyDataSource() {
  17.         logger.trace("Select any dataSource: " + defaultDataSource);
  18.         return defaultDataSource;
  19.     }
  20.     /**
  21.      * Obtains a DataSource based on tenantId
  22.     */
  23.     @Override
  24.     protected DataSource selectDataSource(String tenantIdentifier) {
  25.         DataSource ds = dataSourceLookup.getDataSource(tenantIdentifier);
  26.         logger.trace("Select dataSource from "+ tenantIdentifier+ ": " + ds);
  27.         return ds;
  28.     }
  29. }
复制代码
  DataSourceLookupbean has a map with different datasources mapped by his tenant id, we will write a new post about possible ways to implement this class and how we did it. This will answer the question “ How does Hibernate/Spring know what tenants exist?
   CurrentTenantIdentifierResolver can be implemented in different ways. In our case we decided to take the tenantId from an httpSession attribute. And this is used in throughout Hibernate in this interface.
  1. /**
  2. * It specify what Tenant should be use when the hibernate session is created.
  3. * @author jm
  4. */
  5. public class CurrentTenantIdentifierResolverImpl implements CurrentTenantIdentifierResolver {
  6.     Logger logger = Logger.getLogger(getClass());
  7.     @Override
  8.     public String resolveCurrentTenantIdentifier() {
  9.         String tenant = resolveTenantByHttpSession();
  10.         logger.trace("Tenant resolved: " + tenant);
  11.         return tenant;
  12.     }
  13.     /**
  14.      * Get tenantId in the session attribute KEY_TENANTID_SESSION
  15.      * @return TenantId on KEY_TENANTID_SESSION
  16.      */
  17.     public String resolveTenantByHttpSession()
  18.     {
  19.         ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  20.         //If session attribute exists returns tenantId saved on the session
  21.         if(attr != null){
  22.             HttpSession session = attr.getRequest().getSession(false); // true == allow create
  23.             if(session != null){
  24.                 String tenant = (String) session.getAttribute(KEY_TENANTID_SESSION);
  25.                 if(tenant != null){
  26.                     return tenant;
  27.                 }
  28.             }
  29.         }
  30.         //otherwise return default tenant
  31.         logger.trace("Tenant resolved in session is: " + DEFAULT_TENANTID);
  32.         return DEFAULT_TENANTID;
  33.     }
  34.     @Override
  35.     public boolean validateExistingCurrentSessions() {
  36.         return true;
  37.     }
  38. }
复制代码
How Do We Integrate Multi-Tenancy With JPA?

   To integrate with JPA you must set the jpaPropertyMap(Map<String, ?> properties) in  LocalContainerEntityManagerFactoryBean like this:
  1. <beanclass="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
  2. id="entityManagerFactory">
  3. <property name="persistenceUnitManager" ref="pum"/>
  4. <property name="jpaVendorAdapter">
  5. <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
  6. <property name="databasePlatform" value="${database.dialect}" />
  7. </bean>
  8. </property>
  9. <property name="jpaPropertyMap">
  10.      <map>
  11.           <entry key="hibernate.multi_tenant_connection_provider" value-ref="multitenancyConnectionProvider"/>
  12.        <entry key="hibernate.tenant_identifier_resolver" value-ref="tenantResolver"/>         
  13.      <entry key="hibernate.multiTenancy" value="DATABASE"/>
  14.      </map>
  15. </property>
  16. </bean>
复制代码
If you are using Spring, this can be set in applicationContext.xml.
  In future blog posts we will cover the following topics:
  
       
  • DataSourceLookup implementation for multi-tenancy   
  • Hibernate schema export in multi-tenancy   
  • Different ways to save the tenant id in an http session  
  Finally, I want to share some useful links with you, they helped me to understand multi-tenancy in Hibernate and JPA.
  
       
  •   Hibernate's user guide to multi-tenancy
       
  •   Oracle's persistence package summary
      



上一篇:Working Geek: For Cairn co-founder Ali Alami, getting back to nature is part of
下一篇:用Python进行梯度提升算法的参数调整
刘傲 投递于 2016-12-2 00:08:32
前排,哇咔咔
回复 支持 反对

使用道具 举报

我要投稿

回页顶回复上一篇下一篇回列表
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 | 粤公网安备 44010402000842号 )

© 2001-2017 Comsenz Inc.

返回顶部 返回列表