Spring framework learning [multi-data source configuration optimization]

Source: Internet
Author: User

I wrote spring framework learning [multi-data source configuration], and solved the problem of multi-data source in spring framework through the Decorator mode in design mode, which attracted the attention of many netizens. When discussing the problem with netizens, I found that my solution was not perfect and it only solved some of the problems.

To sum up the problem of multiple data sources, it must be divided into the following three situations: the data structure of each data source is different, the data structure of each data source is the same, and the data structure of each data source is different. In the second case, the data structure of each data source is the same. We use a sessionFactory, and it should be a good solution to dynamically switch the data source through MultiDataSource in sessionFactory, it not only solves the memory waste of repeated loading of multiple sessionFactory objects with the same value, but also makes the data source switch transparent to the customer program, simplifying the implementation of the Code and the impact on the customer program. However, in the first case, the data structures of different data sources are different, and using such a solution poses potential risks.

If the data structure of each data source is different, using a sessionFactory to dynamically switch the data source in this sessionFactory may cause Zhang guanli Dai to access the data. For example, if data source A has table T and Data Source B does not, the client may attempt to connect to data source B when accessing table T, this error is hard to be found because the client program determines which data source to access during the running of the program. A casual error of the customer program may cause an error. There are two ways to solve this problem: first, strict requirements on client programs should not be written incorrectly, which of course can be done, but as a framework designer, another solution is to avoid this situation in the framework. Therefore, I offered a MultiSessionFactory solution to solve the problem of multiple data sources with different data structures.

Problem Analysis

Similar to the MultiDataSource solution, MultiSessionFactory also calls the getBean () method of ApplicationContext in the spring framework without creating beanFacoty. It also uses the Decorator mode to handle switching issues. Object relationship of MultiSessionFactory

 


In this solution, SessionFactory is the org. Hibernate. SessionFactory interface of hibernate, and Decorator is the MultiSessionFactory. SessionFactory1 and SessionFactory2 are usually spring's org. springframework. orm. hibernate3.LocalSessionFactoryBean. Careful friends may note that LocalSessionFactoryBean is not actually the implementation of SessionFactory. Is there a problem with this solution? This problem has actually plagued me for a long time. Finally, I found that when we get a LocalSessionFactoryBean through getBean () of ApplicationContext, we didn't actually get it, instead, we get a SessionFactory because spring overwrites getObject () for LocalSessionFactoryBean so that it returns SessionFactory. A Simple Proof Is That The sessionFactory attribute type of HibernateDaoSupport is SessionFactory, while LocalSessionFactoryBean is injected during spring configuration.

Implementation

In this solution, we only need to implement the MultiSessionFactory class and our cute Spserver class. There are two classes in total, and some spring configurations are complete.

MultiSessionFactory implements SessionFactory and ApplicationContextAware to get the AplicationContext. The code for MultiSessionFactory is as follows:

Java code

Public class MultiSessionFactory implements SessionFactory, ApplicationContextAware {private static final long serialVersionUID = 20645573242034961_l; private static final Log log = LogFactory. getLog (MultiSessionFactory. class); private ApplicationContext applicationContext = null; private SessionFactory sessionFactory = null; public ApplicationContext getApplicationContext () {return applicationContext;} public void setApplicationContext (ApplicationContext applicationContext) {this. applicationContext = applicationContext;} public SessionFactory getSessionFactory (String sessionFactoryName) {log. debug ("sessionFactoryName:" + sessionFactoryName); try {if (sessionFactoryName = null | sessionFactoryName. equals ("") {return sessionFactory;} return (SessionFactory) this. getApplicationContext (). getBean (sessionFactoryName);} catch (NoSuchBeanDefinitionException ex) {throw new DaoException ("There is not the sessionFactory} public SessionFactory getSessionFactory () {String sessionFactoryName = SpObserver. getSp (); return getSessionFactory (sessionFactoryName);} public void setSessionFactory (SessionFactory sessionFactory) {this. sessionFactory = sessionFactory;} // method to be implemented by the SessionFactory interface ......}

For the complete code of MultiSessionFactory, see the attachment I provided. SetSessionFactory () is actually the default sessionFactory. It is called during spring loading. The corresponding data source should be the primary data source, that is, the data source that needs to read the initialization data during project initialization. In any multi-data source project, there should be a data source that stores initialization data, system maintenance data, and user permission data. This is the primary data source. Therefore, the configuration of MultiSessionFactory should be written as follows:

Xml Code

Property>

The SpServer method is the same as that in spring framework learning multi-data source configuration.

In addition, configure multiple data sources in spring configuration. Each Data Source corresponds to one sessionFactory, and the value object in the corresponding sessionFactory should be the value object of the data source. Before executing data access, the customer program calls the SpServer's putSp () method to tell the sessionFactory to be switched to and then executes data access. In this way, the value objects of different data sources are stored in different sessionFactory to avoid the case of Zhang guanli Dai. For specific examples, see the attachment MultiSessionFactoryTest.

Other solutions

Some friends may not be satisfied with the above scheme, because it is necessary to specify sessionFactory step by step before executing data access. In fact, for projects with different data structures of different data sources, a value object has a very definite correspondence with which data source to use. If the value object corresponds to its sessionFactory through the configuration file, which value object is passed during data access execution, MultiSessionFactory can immediately find the corresponding sessionFactory. You can use AOP to create an interceptor to intercept all methods, such as save (), delete (), get (), and load (). You can also use HibernateDaoSupport to implement this scheme. This solution makes the client program even unaware that it is operating a multi-data source system. Of course, friends who are interested in this solution can implement it on their own.

In addition, the core of this solution is to use the Decorator design mode to solve the purpose of switching sessionFactory, that is, the implementation of MultiSessionFactory. You can choose the way to notify the SessionFactory to which the MultiSessionFactory should be switched. I am here to provide you with the SpOberver and the configuration file that establishes the relationship between value objects and sessionFactory. You can also have your own solutions.

Solution in case 3

I have already provided solutions for the first and second cases: MultiSessionFactory is used to solve different data structures of each data source; MultiDataSource is used to solve the problem when the data structures of each data source are the same. In the third case, what should we do if the data structure of each data source is the same and some are different? Of course, it is solved by combining the MultiSessionFactory and MultiDataSource. For different parts of the data structure, they create their respective sessionFactory and then switch through the MultiSessionFactory. For parts with the same data structure, create a common sessionFactory and multiple different dataSource and then use MultiDataSource to switch between them.

Some friends asked about the transaction processing and level-2 cache of such a scheme. This solution is a solution under the spring framework, and its transaction processing capability is also determined by the spring capability. Currently, spring implements cross-Database Transaction processing through JTA. This method can also be implemented in this solution. You can try it. In addition, can this scheme use second-level 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 scruples. For MultiDataSource, this is a problem. MultiDataSource enables multiple data sources to use the same sessionFactory. Therefore, it seems that multiple data sources are logically merged into one data source. Because of this, we need to ensure that the same table must be unique in all data sources. What does it mean? Both data source A and Data Source B have table T. If table T in data source A has A data entry with ID 001, there cannot be A record with ID 001 in table T of data source B. If you always use MultiDataSource to insert a table and use uuid. hex to generate a primary key, this is certainly not a problem. However, if you insert tables in other ways, you should ensure such uniqueness. In addition, for query operations, the cache may store both data from data source A and data from data source B. Therefore, you should have A plan for the data. For data in table T, which data should be inserted into data source A and which should be inserted into data source B should have A definition. If different units are used to determine which data source to insert, then in table T of data source A, the conditions should be added to query only the units that data source A should have, and other units should be excluded. In this way, as long as you notice these two problems, you can use the second-level cache with confidence.

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.