Recently, the business system processes a large amount of data and requires table sharding. Because mybatis is used for persistence, the sharding plug-in can be used directly. The following is a demo.
1. Add Maven dependency to Pom. xml,
<Dependency>
<Groupid> org. shardbatis </groupid>
<Artifactid> shardbatis </artifactid>
<Version> 2.0.0d </version>
</Dependency>
2. mybatis-config.xml configuration file configuration sharding plug-in
<Plugins>
<Plugininterceptor ="Com. Google. Code. shardbatis. plugin. shardplugin">
<Propertyname ="Shardingconfig"Value ="Shard_config.xml"/>
</Plugin>
</Plugins>
3. Implement the sub-table policy interface to obtain the actual table name of the sub-table (the test policy is to calculate the remaining 2 based on the year, and the actual table name is composed of a forward slash and a remainder after the base table name)
Public classShardstrategyimplImplementsShardstrategy {
/**
* Obtain the actual table name.
*@ ParamBasetablename: Logical table name. Generally, it is a table name without a prefix or suffix.
*@ ParamParameter used when Params mybatis executes a statement
*@ ParamMapperid the statement ID configured by mybatis
*@ Return
*/
PublicStringgettargettablename (stringbasetablename, object Params, string mapperid ){
Integerk = 0;
If(Params! =Null){
Shardtestbeanshardtestbean = (shardtestbean) Params;
Integertemp = shardtestbean. getage ();
K = TEMP % 2;
}
ReturnBasetablename + "_" + K;
}
}
4. Configure the sharding configuration file for the sharding Policy
<? Xmlversion ="1.0"Encoding =UTF-8"?>
<! Doctypeshardingconfigpublic "-// shardbatis.googlecode.com//dtdshardbatis 2.0 // en"
Http://shardbatis.googlecode.com/dtd/shardbatis-config.dtd>
<Shardingconfig>
<! -- Optional parselist Configuration
If parselist is configured, only SQL statements within the range of parselist and no longer in ignorelist will be parsed and modified -->
<Parselist> <value> shardtest. addshardtest </value> </parselist>
<! -- Configure a table sharding policy -->
<Strategytablename ="Shard_test"Strategyclass ="Service. shardstrategyimpl"/>
</Shardingconfig>
5. When using shard_test, The sharding plug-in will automatically find the correct table name based on the policy implemented in step 3.
<Insertid ="Addshardtest"Parametertype ="Model. shardtestbean">
Insert into shard_test (username, password, age, remark) values (# {username}, # {password}, # {age}, # {remark })
</Insert>
6. The detailed Code address is as follows (execute database. SQL under resources to create a MySQL sub-table, modify the database username and password of applicationcontext. XML, and run the maven project ):
Http://download.csdn.net/detail/zhulin40/7790399