Maven:
<?xml version= "1.0" encoding= "UTF-8"? ><project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http: Www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0/http Maven.apache.org/xsd/maven-4.0.0.xsd "> <modelVersion>4.0.0</modelVersion> <groupId> Com.fulihui.com</groupid> <artifactId>sharding-jdbc-demo</artifactId> <version>1.0- Snapshot</version> <properties> <project.build.sourceencoding>utf-8</project.build.sourceen Coding> <spring.version>4.1.3.RELEASE</spring.version> <mybatis.version>3.2.4</mybat is.version> <sharding-jdbc.version>1.3.1</sharding-jdbc.version> </properties> <depen dencies> <dependency> <groupId>com.dangdang</groupId> <artifactId> Sharding-jdbc-core</artifactid> <version>${sharding-jdbc.version}</version> <exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </exclusion> <exclusion> <groupId>log4j</groupId> <artifactId>log4j</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.dangdang</groupId> < ;artifactid>sharding-jdbc-transaction</artifactid> <version>${sharding-jdbc.version}</version > <exclusions> <exclusion> <groupid>org.slf4j</groupi D> <artifactId>slf4j-log4j12</artifactId> </exclusion> <exclusion> <groupId>log4j</groupId> <artifactId>log4j</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.dangdang</groupId> <artifactId>sharding-jdbc-config-spring</artifactId> <version>${sharding-jdbc.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <VERSION&G T;4.10</version> <scope>test</scope> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactid>lombok< ;/artifactid> <version>1.16.10</version> </dependency> <dependency> <groupId>Org.springframework</groupid> <artifactId>spring-orm</artifactId> <version>$ {spring.version}</version> </dependency> <dependency> <groupid>commons-db Cp</groupid> <artifactId>commons-dbcp</artifactId> <version>1.4</version& Gt </dependency> <dependency> <groupId>org.mybatis</groupId> <ARTIFAC Tid>mybatis-spring</artifactid> <version>1.2.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <ARTIFACTID>MYBATIS</ARTIFAC tid> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactid>spring-expression</artifacti D> <version>${spring.version}</version> </dependency> <dependency> <g Roupid>org.springframework</groupid> <artifactId>spring-aop</artifactId> <ve rsion>${spring.version}</version> </dependency> <dependency> <groupId> Org.springframework</groupid> <artifactId>spring-beans</artifactId> <version> ;${spring.version}</version> </dependency> <dependency> <groupid>org.spri Ngframework</groupid> <artifactId>spring-context</artifactId> <VERSION>${SPR ing.version}</version> <exclusions> <exclusion> <groupid >org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </ex Clusion> <exclusion> <groupId>log4j</groupId> <artifactid>log4j< ;/artifactid> </exclusion> </exclusions> </dependency> <de Pendency> <groupId>org.springframework</groupId> <artifactid>spring-context-sup Port</artifactid> <version>${spring.version}</version> </dependency> < Dependency> <groupId>org.springframework</groupId> <artifactid>spring-test</ artifactid> <version>${spring.version}</version> </dependency> <dependenc Y> <groupId>org.springframework</groupId> <artifactid>spring-tx</artifactid& Gt <version>${spring.version}</version> </dependency> <dependency> <group Id>mysQl</groupid> <artifactId>mysql-connector-java</artifactId> <VERSION>5.1.28&L T;/version> </dependency> </dependencies></project>
To build a table statement:
SETforeign_key_checks=0;--------------------------------Table structure for t_student_0----------------------------- -DROP TABLEIFEXISTS' T_student_0 ';CREATE TABLE' T_student_0 ' (' ID ')int(11)Not NULLAuto_increment, ' student_id 'int(11)Not NULL, ' name 'varchar(255)Not NULL, ' age 'int(11)Not NULL,PRIMARY KEY(' ID ')) Engine=innodbDEFAULTCharset=utf8;DROP TABLEIFEXISTS' T_student_1 ';CREATE TABLE' T_student_1 ' (' ID ')int(11)Not NULLAuto_increment, ' student_id 'int(11)Not NULL, ' name 'varchar(255)Not NULL, ' age 'int(11)Not NULL,PRIMARY KEY(' ID ')) Engine=innodbDEFAULTCharset=utf8;DROP TABLEIFEXISTS' T_user_0 ';CREATE TABLE' T_user_0 ' (' ID ')int(11)Not NULLAuto_increment, ' user_id 'int(11)Not NULL, ' name 'varchar(255)Not NULL, ' age 'int(11)Not NULL,PRIMARY KEY(' ID ')) Engine=innodbDEFAULTCharset=utf8;DROP TABLEIFEXISTS' T_user_1 ';CREATE TABLE' T_user_1 ' (' ID ')int(11)Not NULLAuto_increment, ' user_id 'int(11)Not NULL, ' name 'varchar(255)Not NULL, ' age 'int(11)Not NULL,PRIMARY KEY(' ID ')) Engine=innodbDEFAULTCharset=utf8;DROP TABLEIFEXISTS' T_user_2 ';CREATE TABLE' T_user_2 ' (' ID ')int(11)Not NULLAuto_increment, ' user_id 'int(11)Not NULL, ' name 'varchar(255)Not NULL, ' age 'int(11)Not NULL,PRIMARY KEY(' ID ')) Engine=innodbDEFAULTCharset=utf8;
Spring Configuration:
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns:rdb= "Http://www.dangdang.com/schema/ddframe/rdb" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx.xsd Http://www.dangdang.com/schema/ddframe/rdb http://www.dangdang.com/schema/ddframe/rdb/rdb.xsd " > <context:component-scan base-package= "com.fulihui.sharding.jdbc"/> <bean class= " Org.mybatis.spring.mapper.MapperScannerConfigurer "> <property name=" basepackage "value=" Com.fulihuI.sharding.jdbc.dal.mapper "/> <property name=" sqlsessionfactorybeanname "value=" SqlSessionFactory "/> &L t;/bean> <!--configuration Sqlsessionfactory--<bean id= "sqlsessionfactory" class= "org.mybatis.spring.SqlSes Sionfactorybean "> <property name=" dataSource "ref=" Shardingdatasource "/> <property name=" MapperL Ocations "value=" Classpath*:config/mapper/*-mapper.xml "/> </bean> <!--routing table, routing library rule configuration, You can specify that algorithm-class specifically implement the specific routing rules itself, or you can use the expression---<rdb:strategy id= "Userdatabaseshardingstrategy" sharding-columns= "user_id" algorithm-class= "Com.fulihui.sharding.jdbc.algorithm.UserDatabaseShardingAlgorithm"/ > <rdb:strategy id= "usertableshardingstrategy" sharding-columns= "user_id" algorithm-class= " Com.fulihui.sharding.jdbc.algorithm.UserTableShardingAlgorithm "/> <!--using expressions--<rdb:strategy id=" St Udentdatabaseshardingstrategy "sharding-columns=" student_id "algorithm-expression=" Sharding_${studeNt_id.longvalue ()% 2} "/> <rdb:strategy id=" studenttableshardingstrategy "sharding-columns=" student_id " Algorithm-expression= "T_student_${student_id.longvalue ()% 2}"/> <rdb:data-source id= "ShardingDataSource" > <rdb:sharding-rule data-sources= "sharding_0,sharding_1" > <rdb:table-rules> <rdb:table-rule logic-table= "T_user" actual-tables= "sharding_${0..1}.t_user_${0..2}" database-strategy= " Userdatabaseshardingstrategy "table-strategy=" Usertableshardingstrategy "/> <rdb:table-rule logic-tabl E= "T_student" actual-tables= "sharding_${0..1}.t_student_${0..1}" database-strategy= " Studentdatabaseshardingstrategy "table-strategy=" Studenttableshardingstrategy "/> </rdb:table-rules> <rdb:default-database-strategy sharding-columns= "None" algorithm-class= "Com.dangdang.ddframe.rdb.sharding.api . Strategy.database.NoneDatabaseShardingAlgorithm "/> <rdb:default-table-straTegy sharding-columns= "None" algorithm-class= " Com.dangdang.ddframe.rdb.sharding.api.strategy.table.NoneTableShardingAlgorithm "/> </rdb:sharding-rule > <rdb:props> <prop key= "metrics.enable" >false</prop> </rdb:props> </rdb:data-source> <!--transactions-<bean id= "TransactionManager" class= "Org.springframework.jdbc . DataSource. Datasourcetransactionmanager "> <property name=" dataSource "ref=" Shardingdatasource "/> </bean> <tx:annotation-driven transaction-manager= "TransactionManager"/></beans>
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context.xsd "> <context:property-placeholder location=" classpath:config/resource/jdbc_dev.properties "Ignore-unresolvable=" true "/> <bean name=" sharding_0 "class=" Com.alibaba.druid.pool.DruidDataSource " Init-method= "Init" destroy-method= "close" > <property name= "url" value= "${jdbc_url0}"/> <property na Me= "username" value= "${JDBC_USERNAME0}"/> <property name= "password" value= "${jdbc_password0}"/> <! --Initialize connection size--<property name= "initialsize" value= "0"/> <! --Connection pool maximum usage connections--<property name= "maxactive" value= "/> <!--connection Pool min Idle--<property NA Me= "Minidle" value= "0"/> <!--get connection maximum wait time-<property name= "maxwait" value= "60000"/> < Property Name= "Validationquery" value= "${validationquery}"/> <property name= "Testonborrow" value= "false"/> <property name= "Testonreturn" value= "false"/> <property name= "Testwhileidle" value= "true"/> < how long!--configuration interval to detect idle connections that need to be closed, in milliseconds-<property name= "Timebetweenevictionrunsmillis" value= "60000"/> <!--Configure the minimum lifetime of a connection in the pool, in milliseconds-<property name= "Minevictableidletimemillis" value= "25200000"/> <!--open removeabandoned function--<property name= "removeabandoned" value= "true"/> <!--1800 seconds, which is 30 minutes Clock--<property name= "removeabandonedtimeout" value= "1800"/> <!--output error log when abanded connection is off--&L T;property name= "LogabAndoned "value=" true "/> <property name=" Filters "value=" stat "/> </bean> <bean name=" Sharding_ 1 "class=" Com.alibaba.druid.pool.DruidDataSource "init-method=" Init "destroy-method=" close "> <property name=" URL "value=" ${jdbc_url1} "/> <property name=" username "value=" ${jdbc_username1} "/> <property name=" Password "value=" ${jdbc_password1} "/> <!--Initialize connection size--<property name=" initialsize "value=" 0 "/> <!--connection Pool maximum usage connections-<property name= "maxactive" value= "/> <!--connection Pool min Idle--< Property Name= "Minidle" value= "0"/> <!--get connection maximum wait time-<property name= "maxwait" value= "60000"/> ; <property name= "Validationquery" value= "${validationquery}"/> <property name= "TestOnBorrow" value= "false"/ > <property name= "Testonreturn" value= "false"/> <property name= "Testwhileidle" value= "true"/> < How long does the!--configuration intervalPerform a test to detect idle connections that need to be closed, in milliseconds-<property name= "Timebetweenevictionrunsmillis" value= "60000"/> <!--configuration The minimum time for a connection to survive in a pool, in milliseconds-<property name= "Minevictableidletimemillis" value= "25200000"/> <!--Open Remo veabandoned function--<property name= "removeabandoned" value= "true"/> <!--1800 seconds, i.e. 30 minutes---&L T;property name= "removeabandonedtimeout" value= "1800"/> <!--off abanded connection output error log--<property name= "Logabandoned" value= "true"/> <property name= "Filters" value= "stat"/> </bean></beans>
Add, delete, change, check the interface code is not affixed.
Test class:
@RunWith (Springjunit4classrunner.class) @ContextConfiguration (locations = {"Classpath*:config/spring/spring-datab Ase.xml "," Classpath*:config/spring/spring-sharding.xml "}) public class Shardingjdbcmybatistest {@Resource p Ublic UserService UserService; @Resource public Studentservice Studentservice; @Test public void Testuserinsert () {Userdo u = new Userdo (); U.setuserid (9); U.setage (25); U.setname ("Levon"); Assert.assertequals (Userservice.insert (U), true); } @Test public void Teststudentinsert () {studentdo studentdo = new Studentdo (); Studentdo.setstudentid (9); Studentdo.setage (21); Studentdo.setname ("hehe"); Assert.assertequals (Studentservice.insert (STUDENTDO), true); } @Test public void Testfindall () {list<userdo> Userdos = Userservice.findall (); if (null! = Userdos &&!) Userdos.isempty ()) {for (Userdo U:userdos) { System. out. println (U); }}} @Test public void Testsqlin () {list<userdo> Userdos = Userservice.findbyuserids (Arr Ays.aslist (12,14,17)); if (null! = Userdos &&!) Userdos.isempty ()) {for (Userdo u:userdos) {System. out. println (U); }}} @Test public void Testtransactiontestsucess () {userservice.transactiontestsucess (); } @Test (expected = illegalaccessexception.class) public void Testtransactiontestfailure () throws Illegalaccessex ception{userservice.transactiontestfailure (); } }
SHARDING-JDBC Integrated Spring+mybatis Sub-table sub-Library