Re-analysis of problems in solving multi-data sources in spring framework

Source: Internet
Author: User
Tags log log

In front I wrote "How to solve the problem of multi-data source in spring Framework", through the design pattern of the decorator model in the spring framework to solve the problem of multi-data sources, has been a lot of netizens attention. In the process of discussing the problem with netizens, I found that my plan was not perfect, it only solved a part of the problem.

Summing up the problem of multi-data sources, in fact, it needs to be divided into the following three situations: the data structure of each data source is different, the data structure of each source is the same, the data structure of each source part is the same and partly different. For the second case, the data structure of each source is the same, we use a sessionfactory, and in the sessionfactory through the Multidatasource to dynamically switch the data source, it should be a good solution, It solves both the waste of memory of repeated loading of multiple sessionfactory on the same value object, and the transparency of the switching of the data source to the client program, which simplifies the implementation of the Code and the impact on the client program. However, for the first case, the data structure of each data source is different, and the use of such a scenario has a potential risk.

For the data structure of each data source is different, using a sessionfactory to dynamically switch data sources in this sessionfactory can result in pigtailed of data access. For example, the data source A has a table T and data source B does not, may cause the client program to access the table T when the attempt to connect to data source B, because the client program access to which data source is determined during the program run by the client program, so such errors are difficult to find. Perhaps an inadvertent error in the client's program can cause errors. There are two ways to solve this problem: first, the strict requirements of the client program not to write wrong, this is certainly possible, but as a framework designer, another solution is to avoid such a situation in the framework. So I sacrificed a multisessionfactory solution to solve multiple data source problems with different data structures for each data source.

Analysis of the problem

As with Multidatasource's scenario, Multisessionfactory also calls ApplicationContext's Getbean () method under the spring framework without creating another beanfacoty, Also use the decorator mode to handle switching problems. Object Relationship of Multisessionfactory

In this scenario, Sessionfactory is Hibernate's Org.hibernate.SessionFactory interface, decorator is multisessionfactory,sessionfactory1 and SessionFactory2 often It's spring's org.springframework.orm.hibernate3.LocalSessionFactoryBean. Careful friends may notice, in fact, Localsessionfactorybean is not the implementation of sessionfactory, the solution is there a problem? This problem has been troubling me for a long time, and finally I found that we get a localsessionfactorybean by ApplicationContext's Getbean () actually not really get it, Instead, a sessionfactory is obtained because spring rewrites the GetObject () for Localsessionfactorybean, which returns the Sessionfactory. A simple proof is that the type of the Sessionfactory property of the Hibernatedaosupport is sessionfactory, and we inject localsessionfactorybean in the spring configuration. Implementation of the scheme

Throughout this scenario, we need to implement only the Multisessionfactory class and our lovely spserver, a total of two classes, then a few spring configurations, it is done.

Multisessionfactory realizes the Sessionfactory, and realizes the Applicationcontextaware in order to get aplicationcontext. The code for Multisessionfactory is as follows:

Java code
 Public classMultisessionfactoryImplementsSessionfactory, Applicationcontextaware {Private Static Final LongSerialversionuid = 2064557324203496378L; Private Static FinalLog log = Logfactory.getlog (multisessionfactory.class); PrivateApplicationContext ApplicationContext =NULL; PrivateSessionfactory sessionfactory =NULL;  PublicApplicationContext Getapplicationcontext () {returnApplicationContext; }        Public voidSetapplicationcontext (ApplicationContext applicationcontext) { This. ApplicationContext =ApplicationContext; }        Publicsessionfactory getsessionfactory (String sessionfactoryname) {log.debug ("Sessionfactoryname:" +sessionfactoryname); Try{              if(sessionfactoryname==NULL|| Sessionfactoryname.equals ("")){                 returnsessionfactory; }              return(sessionfactory) This. Getapplicationcontext (). Getbean (Sessionfactoryname); }Catch(Nosuchbeandefinitionexception ex) {Throw NewDaoexception ("There is not the Sessionfactory       }       }          Publicsessionfactory getsessionfactory () {String sessionfactoryname=spobserver.getsp (); returngetsessionfactory (sessionfactoryname); }          Public voidsetsessionfactory (sessionfactory sessionfactory) { This. Sessionfactory =sessionfactory; }         //Sessionfactory interface needs to implement the method  ......     } 

Multisessionfactory's complete code is available in the annex I provide. Setsessionfactory () is actually the default sessionfactory set, which is called when spring loads, and its corresponding data source should be the primary data source, which is the data source that needs to read the initialization data in the project initialization. In any multi-data source project, there should be a data source that holds initialization data, system maintenance data, and user rights data, which is the primary data source. So the configuration of multisessionfactory should be written like this:

XML code
<id= "Sessionfactory"  class= " Com.htxx.service.dao.MultiSessionFactory ">      <name=" Sessionfactory "><bean=" hostsessionfactory "/>  property> >

The way Spserver is written is the same as the question of how to solve multiple data sources in the spring framework, and I'm no longer a liability.

Also, configure multiple data sources in the spring configuration, one for each sessionfactory, and the value object in the corresponding sessionfactory to be the value object for that data source. Before performing data access, the client tells Multisessionfactory which sessionfactory to switch to and then performs data access by calling Spserver's Putsp () method. Thus, the value objects of different data sources are avoided by placing them in different sessionfactory. Pigtailed. For a specific example, see the multisessionfactorytest of the attachment.

Another solution

Perhaps some friends are not satisfied with the above scheme, because after all, it is more a step to specify Sessionfactory's work before performing the data access. In fact, for items with different data structures for each data source, a value object should use which data source has a very deterministic correspondence. If the value object is mapped to its sessionfactory by a configuration file, then the value object is passed when we perform the data access, and Multisessionfactory can immediately find the corresponding sessionfactory. In this scenario, you can use AOP to make an interceptor that intercepts all methods such as Save (), delete (), get (), load (), or extend Hibernatedaosupport to implement. Such a scheme allows the client program to not even know that he is operating in a multi-data source system. Of course, this program is interested in friends can be realized on their own.

In addition, the core of this scheme is to use decorator design pattern to solve the purpose of switching sessionfactory, that is, the realization of multisessionfactory. As to what way to inform Multisessionfactory should switch to which sessionfactory, according to the situation of different projects freely choose. I am here to provide you with a configuration file with Spoberver and sessionfactory relationships through the two scenarios, you can also have your own solution.

Solutions for the third scenario

Before I have given the first and second cases of the solution: the data structure of the various data sources with multisessionfactory solution, the data structure of the various sources of the same situation with the Multidatasource solution. So in the third case, the data structure of each source is part of the same and partly different, and how should it be solved? Of course, multisessionfactory and Multidatasource are combined to solve. For different parts of the data structure, they create their own sessionfactory and then switch through the multisessionfactory, and for the same part of the data structure, Build common sessionfactory and multiple different datasource and then switch through Multidatasource to be able to.

Some friends ask this scenario for their transactional processing and level two caching. This solution is a solution under the spring framework, and the ability of the transaction processing is determined by spring's ability. The current spring to handle cross-database transactions is implemented through JTA, which can also be implemented in this scenario, friends can try. In addition, can the program use a level two cache? Of course. Of course there is no problem with multisessionfactory, it leaves different data sources and value objects through different sessionfactory, and we can use them without scruple. For Multidatasource, there is a problem. Multidatasource enables multiple data sources to use a common sessionfactory, so it is as if multiple data sources are logically merged into one data source. Because of this, we need to make sure that the primary key is unique across all data sources for the same table. What do you mean? Both data source A and data source B have table T, and if table T in data source A has a data ID of 001, then there is no record of ID 001 in table T in data source B. If you are always using Multidatasource to perform insert operations on the table and use Uuid.hex to generate the primary key, this is of course not a problem. But if you have any other way of inserting a table, you should ensure that this uniqueness is true. In addition, for the operation of the query, the cache can be stored in either data source A or data source B data, so you should have a plan for the data. For data in table T, which should be inserted into data source A and which should be inserted into B, there should be a definition. If you are deciding which data source to insert through different units, then in query data source a the table T is, you should increase the condition only query data source A should have units and exclude the other units. In this way, you can confidently use level two caching as long as you notice these two issues.
    • Example.rar (16.4 KB)
    • Description: Sample File
    • Download number of times: 3620
    • View Picture Attachments

Reference article: http://www.iteye.com/topic/91667

Re-analysis of problems in solving multi-data sources in spring framework

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.