Spring Boot 结合 Sharding-Jdbc做分库分表示例

对于一些大系统,数据库数据量很大,业务量特别大的时候,而我们的数据库及表的对于大数据量的时候,处理的性能就不容乐观,这个时候我们就需要对我们的数据和表做分库分表处理了。一般分库分表都会采用数据库中间件,像Mycat这种中间件,它帮我们做数据源,路由映射控制。而今天介绍的Sharding-Jdbc是一个java的应用程序包,所以两者一比较,中间件肯定更加重量级一些。

添加POM依赖:

<?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.chown.pine.sharding</groupId>
    <artifactId>chown-sharding-jdbc</artifactId>
    <version>1.0</version>

    <name>chown-sharding-jdbc</name>
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <mybatis.version>3.4.6</mybatis.version>
        <mybatis.spring.version>1.3.2</mybatis.spring.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>spring-boot-starter-logging</artifactId>
                    <groupId>org.springframework.boot</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.dangdang</groupId>
            <artifactId>sharding-jdbc-core</artifactId>
            <version>1.5.4.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis.spring.version}</version>
        </dependency>
    </dependencies>
</project>

YAML配置

# 公钥
public:
  key: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJZtfAfaggxBRhuaJeE9KMSIqPpAxbUQRTAjzoSaVqt/8wqd3crYeS2Ebxt2fWHDOQSTpPZfl1+whyMMEtq5vcMCAwEAAQ==
spring:
  datasource:
    # 数据库数据源 1
    ds0:
      username: test01
      # ;config.decrypt=true;config.decrypt.key=${public.key}  U4A5Uv3UHPLtjk1dgw1/+WNP3pIlc8lBDYswjwQ2zS+3NKij1NsFzggxKudLuuerc2Wcgnj4P60VrqQzh7VISQ==
      password: U4A5Uv3UHPLtjk1dgw1/+WNP3pIlc8lBDYswjwQ2zS+3NKij1NsFzggxKudLuuerc2Wcgnj4P60VrqQzh7VISQ==
      url: jdbc:mysql://192.168.0.11:21000/t_db_1?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=utf-8
      type: com.alibaba.druid.pool.DruidDataSource
      connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000;config.decrypt=true;config.decrypt.key=${public.key}
    # 数据库数据源 2
    ds1:
      username: test02
      password: U4A5Uv3UHPLtjk1dgw1/+WNP3pIlc8lBDYswjwQ2zS+3NKij1NsFzggxKudLuuerc2Wcgnj4P60VrqQzh7VISQ==
      url: jdbc:mysql://192.168.0.11:21000/t_db_2?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=utf-8
      type: com.alibaba.druid.pool.DruidDataSource
      connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000;config.decrypt=true;config.decrypt.key=${public.key}

Druid数据库连接属性配置(datasource.properties):

#初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时
druid.initialSize=1
#最小连接池数量
druid.minIdle=1
#最大连接池数量 default : 8
druid.maxActive=50
#申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
druid.testOnBorrow=true
#获取连接时最大等待时间,单位毫秒
druid.maxWait=60000
# 有两个含义:
# 1) Destroy线程会检测连接的间隔时间
# 2) testWhileIdle的判断依据,详细看testWhileIdle属性的说明
druid.timeBetweenEvictionRunsMillis=60000
druid.minEvictableIdleTimeMillis=300000
#用来检测连接是否有效的sql,要求是一个查询语句。
druid.validationQuery=SELECT 1 FROM DUAL
#建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis 执行validationQuery检测连接是否有效。
druid.testWhileIdle=true
#归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
druid.testOnReturn=false
#是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql5.5以下的版本中没有PSCache功能,建议关闭掉。
druid.poolPreparedStatements=false
druid.maxPoolPreparedStatementPerConnectionSize=20
#属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:
#   监控统计用的filter:stat
#   日志用的filter:log4j
#   防御sql注入的filter:wall
druid.filters=stat,wall,config

数据源DataSource配置:

package com.chown.pine.sharding.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.dangdang.ddframe.rdb.sharding.api.ShardingDataSourceFactory;
import com.dangdang.ddframe.rdb.sharding.api.rule.BindingTableRule;
import com.dangdang.ddframe.rdb.sharding.api.rule.DataSourceRule;
import com.dangdang.ddframe.rdb.sharding.api.rule.ShardingRule;
import com.dangdang.ddframe.rdb.sharding.api.rule.TableRule;
import com.dangdang.ddframe.rdb.sharding.api.strategy.database.DatabaseShardingStrategy;
import com.dangdang.ddframe.rdb.sharding.api.strategy.table.TableShardingStrategy;
import lombok.Getter;
import lombok.Setter;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.*;

/**
 * <数据源配置>
 *
 * @author zping
 * @version 2018/11/22 0022
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Getter
@Setter
@Configuration
@PropertySource (value = { "classpath:/datasource.properties" }, encoding = "UTF-8")
@ConfigurationProperties (prefix = "druid")
public class DataSourceConfig
{

	/**
	 * 实体类包路径
	 */
	private static final String ENTITY_SCAN_PATH = "com.chown.pine.sharding.database.entity";

	/**
	 * mybatis配置文件路径
	 */
	private static final String MYBATIS_CONFIG_PATH = "classpath:/mybatis-config.xml";

	/**
	 * mybatis映射文件路径
	 */
	private static final String MAPPER_PATH = "classpath:/mapper/*.xml";

	/**
	 * 心跳检测SQL
	 */
	private String validationQuery;

	private Boolean testWhileIdle;

	private Boolean testOnBorrow;

	private Boolean testOnReturn;

	private Boolean poolPreparedStatements;

	/**
	 * 最大等待数
	 */
	private Integer maxWait;

	/**
	 * 最大活跃数
	 */
	private Integer maxActive;

	/**
	 * 最小空闲数
	 */
	private Integer minIdle;

	/**
	 * 初始化连接数
	 */
	private Integer initialSize;

	/**
	 * 配置过滤器(注意:如果使用了Druid的密码加密,一定要配置过滤器config,要不然他无法解密数据库密码)
	 */
	private String filters;

	private Integer timeBetweenEvictionRunsMillis;

	private Integer minEvictableIdleTimeMillis;

	private Integer maxPoolPreparedStatementPerConnectionSize;

	/**
	 * 配置数据源0,数据源的名称最好要有一定的规则,方便配置分库的计算规则
	 *
	 * @return
	 */
	@Bean (name = "dataSource0")
	@ConfigurationProperties (prefix = "spring.datasource.ds0")
	public DruidDataSource dataSource0 ()
	{
		DruidDataSource dataSource0 = new DruidDataSource ();
		dataSource0.setMinIdle (minIdle);
		dataSource0.setMaxActive (maxActive);
		dataSource0.setInitialSize (initialSize);
		dataSource0.setMinEvictableIdleTimeMillis (minEvictableIdleTimeMillis);
		dataSource0.setTimeBetweenConnectErrorMillis (timeBetweenEvictionRunsMillis);
		dataSource0.setMaxPoolPreparedStatementPerConnectionSize (maxPoolPreparedStatementPerConnectionSize);
		dataSource0.setMaxWait (maxWait);
		dataSource0.setTestWhileIdle (testWhileIdle);
		dataSource0.setTestOnReturn (testOnReturn);
		dataSource0.setTestOnBorrow (testOnBorrow);
		dataSource0.setValidationQuery (validationQuery);
		dataSource0.setPoolPreparedStatements (poolPreparedStatements);
		try
		{
			dataSource0.setFilters (filters);
		}
		catch (SQLException e)
		{
			e.printStackTrace ();
		}
		return dataSource0;
	}

	/**
	 * 配置数据源1,数据源的名称最好要有一定的规则,方便配置分库的计算规则
	 *
	 * @return
	 */
	@Bean (name = "dataSource1")
	@ConfigurationProperties (prefix = "spring.datasource.ds1")
	public DruidDataSource dataSource1 ()
	{
		DruidDataSource dataSource1 = new DruidDataSource ();
		dataSource1.setInitialSize (initialSize);
		dataSource1.setMaxActive (maxActive);
		dataSource1.setMinIdle (minIdle);
		dataSource1.setTimeBetweenConnectErrorMillis (timeBetweenEvictionRunsMillis);
		dataSource1.setMinEvictableIdleTimeMillis (minEvictableIdleTimeMillis);
		dataSource1.setTestOnBorrow (testOnBorrow);
		dataSource1.setTestOnReturn (testOnReturn);
		dataSource1.setTestWhileIdle (testWhileIdle);
		dataSource1.setMaxWait (maxWait);
		dataSource1.setPoolPreparedStatements (poolPreparedStatements);
		dataSource1.setValidationQuery (validationQuery);
		try
		{
			dataSource1.setFilters (filters);
		}
		catch (SQLException e)
		{
			e.printStackTrace ();
		}
		return dataSource1;
	}

	/**
	 * 配置数据源规则,即将多个数据源交给sharding-jdbc管理,并且可以设置默认的数据源,
	 * 当表没有配置分库规则时会使用默认的数据源
	 *
	 * @return
	 */
	@Bean
	public DataSourceRule dataSourceRule (@Qualifier ("dataSource0") DruidDataSource dataSource0,
			@Qualifier ("dataSource1") DruidDataSource dataSource1)
	{
		//设置分库映射
		Map<String, DataSource> dataSourceMap = new HashMap<> ();
		dataSourceMap.put ("dataSource0", dataSource0);
		dataSourceMap.put ("dataSource1", dataSource1);
		//设置默认库,两个库以上时必须设置默认库。默认库的数据源名称必须是dataSourceMap的key之一
		return new DataSourceRule (dataSourceMap, "dataSource0");
	}

	/**
	 * 配置数据源策略和表策略,具体策略需要自己实现
	 *
	 * @param dataSourceRule
	 * @return
	 */
	@Bean
	public ShardingRule configShardingRule (DataSourceRule dataSourceRule)
	{
		//配置分库分表策略
		TableRule orderTableRule = TableRule.builder ("t_order")
				//设置物理表
				.actualTables (Arrays.asList ("t_order_0", "t_order_1"))
				//设置分表策略
				.tableShardingStrategy (new TableShardingStrategy ("order_id", new ModuloTableShardingAlgorithm ()))
				//设置数据源
				.dataSourceRule (dataSourceRule).build ();

		//绑定表策略,在查询时会使用主表策略计算路由的数据源,因此需要约定绑定表策略的表的规则需要一致,可以一定程度提高效率
		List<BindingTableRule> bindingTableRules = new ArrayList<> ();
		bindingTableRules.add (new BindingTableRule (Arrays.asList (orderTableRule)));

		//构建分库分表策略规则
		return ShardingRule.builder ()
				//设置数据源策略规则
				.dataSourceRule (dataSourceRule)
				//设置分表策略规则
				.tableRules (Arrays.asList (orderTableRule))
				//绑定分表策略
				.bindingTableRules (bindingTableRules)
				//设置分库策略
				.databaseShardingStrategy (
						new DatabaseShardingStrategy ("user_id", new ModuloDatabaseShardingAlgorithm ()))
				//分表策略
				.tableShardingStrategy (new TableShardingStrategy ("order_id", new ModuloTableShardingAlgorithm ()))
				.build ();
	}

	/**
	 * 创建sharding-jdbc的数据源DataSource, MyBatisAutoConfiguration会使用此数据源
	 *
	 * @param shardingRule 分库分表策略配置
	 * @return
	 * @throws SQLException
	 */
	@Bean (name = "dataSource")
	public DataSource shardingDataSource (ShardingRule shardingRule) throws SQLException
	{
		return ShardingDataSourceFactory.createDataSource (shardingRule);
	}

	/**
	 * 创建SQLSessionFactory工厂对象
	 *
	 * @param dataSource
	 * @return
	 */
	@Bean (name = "sqlSessionFactory")
	public SqlSessionFactory sqlSessionFactory (DataSource dataSource)
	{
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean ();
		sqlSessionFactoryBean.setDataSource (dataSource);

		/*扫描DOMAIN包,可以使用别名*/
		sqlSessionFactoryBean.setTypeAliasesPackage (ENTITY_SCAN_PATH);

		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver ();

		try
		{
			/*扫描mybatis配置文件*/
			sqlSessionFactoryBean.setConfigLocation (resolver.getResource (MYBATIS_CONFIG_PATH));
			sqlSessionFactoryBean.setMapperLocations (resolver.getResources (MAPPER_PATH));
			return sqlSessionFactoryBean.getObject ();
		}
		catch (Exception e)
		{
			e.printStackTrace ();
			return null;
		}
	}

	/**
	 * 创建SqlSessionTemplate模板对象
	 *
	 * @param sqlSessionFactory
	 * @return
	 */
	@Bean
	public SqlSessionTemplate sqlSessionTemplate (SqlSessionFactory sqlSessionFactory)
	{
		return new SqlSessionTemplate (sqlSessionFactory);
	}
}

MyBatias配置扫描Mapper:

package com.chown.pine.sharding.config;

import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <配置Mapper扫描>
 *
 * @author zping
 * @version 2018/4/12 0012
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Configuration
public class MapperScanConfig
{
	/**
	 * Mapper 扫描路径
	 */
	private static final String MAPPER_PACK = "com.chown.pine.sharding.database.mapper";

	@Bean
	public MapperScannerConfigurer mapperScannerConfigurer ()
	{
		MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer ();
		mapperScannerConfigurer.setSqlSessionFactoryBeanName ("sqlSessionFactory");
		mapperScannerConfigurer.setBasePackage (MAPPER_PACK);
		return mapperScannerConfigurer;
	}
}

实现Sharding-Jdbc简单分库策略配置:

package com.chown.pine.sharding.config;

import com.dangdang.ddframe.rdb.sharding.api.ShardingValue;
import com.dangdang.ddframe.rdb.sharding.api.strategy.database.SingleKeyDatabaseShardingAlgorithm;
import com.google.common.collect.Range;

import java.util.Collection;
import java.util.LinkedHashSet;

/**
 * <简单分库策略实现>
 *
 * @author zping
 * @version 2018/11/22 0022
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class ModuloDatabaseShardingAlgorithm implements SingleKeyDatabaseShardingAlgorithm<Long>
{

	/**
	 * 键值分库策略处理
	 *
	 * @param databaseNames 数据库名称集合
	 * @param shardingValue 分库策略配置字段值(如:user_id)
	 * @return
	 */
	@Override
	public String doEqualSharding (Collection<String> databaseNames, ShardingValue<Long> shardingValue)
	{
		for (String databaseName : databaseNames)
		{
			if (databaseName.endsWith (shardingValue.getValue () % 2 + ""))
			{
				return databaseName;
			}
		}
		throw new IllegalArgumentException ();
	}

	/**
	 * In 查询处理策略
	 *
	 * @param databaseNames
	 * @param shardingValue
	 * @return
	 */
	@Override
	public Collection<String> doInSharding (Collection<String> databaseNames, ShardingValue<Long> shardingValue)
	{
		Collection<String> result = new LinkedHashSet<> (databaseNames.size ());

		for (Long tablesShardingValue : shardingValue.getValues ())
		{
			for (String tableName : databaseNames)
			{
				if (tableName.endsWith (tablesShardingValue % 2 + ""))
				{
					result.add (tableName);
				}
			}
		}
		return result;
	}

	/**
	 * Between方式查询处理策略
	 *
	 * @param databaseNames 数据库集合
	 * @param shardingValue 分库键值逻辑值集合
	 * @return
	 */
	@Override
	public Collection<String> doBetweenSharding (Collection<String> databaseNames, ShardingValue<Long> shardingValue)
	{
		Collection<String> result = new LinkedHashSet<> (databaseNames.size ());
		Range<Long> range = (Range<Long>) shardingValue.getValueRange ();
		for (Long i = range.lowerEndpoint (); i <= range.upperEndpoint (); i++)
		{
			for (String databaseName : databaseNames)
			{
				if (databaseName.endsWith (i % 2 + ""))
				{
					result.add (databaseName);
				}
			}
		}
		return result;
	}
}

配置Sharding-Jdbc分表策略:

package com.chown.pine.sharding.config;

import com.dangdang.ddframe.rdb.sharding.api.ShardingValue;
import com.dangdang.ddframe.rdb.sharding.api.strategy.table.SingleKeyTableShardingAlgorithm;
import com.google.common.collect.Range;

import java.util.Collection;
import java.util.LinkedHashSet;

/**
 * <简单分表策略实现>
 *
 * @author zping
 * @version 2018/11/22 0022
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class ModuloTableShardingAlgorithm implements SingleKeyTableShardingAlgorithm<Long>
{
	@Override
	public String doEqualSharding (Collection<String> tableNames, ShardingValue<Long> shardingValue)
	{
		for (String tableName : tableNames)
		{
			if (tableName.endsWith (shardingValue.getValue () % 2 + ""))
			{
				return tableName;
			}
		}
		throw new IllegalArgumentException ();
	}

	@Override
	public Collection<String> doInSharding (Collection<String> tableNames, ShardingValue<Long> shardingValue)
	{
		Collection<String> result = new LinkedHashSet<> (tableNames.size ());
		for (Long value : shardingValue.getValues ())
		{
			for (String tableName : tableNames)
			{
				if (tableName.endsWith (value % 2 + ""))
				{
					result.add (tableName);
				}
			}
		}
		return result;
	}

	@Override
	public Collection<String> doBetweenSharding (Collection<String> tableNames, ShardingValue<Long> shardingValue)
	{
		Collection<String> result = new LinkedHashSet<> (tableNames.size ());
		Range<Long> range = (Range<Long>) shardingValue.getValueRange ();
		for (Long i = range.lowerEndpoint (); i <= range.upperEndpoint (); i++)
		{
			for (String each : tableNames)
			{
				if (each.endsWith (i % 2 + ""))
				{
					result.add (each);
				}
			}
		}
		return result;
	}
}

Mapper实现:

package com.chown.pine.sharding.database.mapper;

import com.chown.pine.sharding.database.entity.Order;

import java.util.List;

/**
 * <一句话功能简述> <功能详细描述>
 *
 * @author zping
 * @version 2018/11/23 0023
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public interface OrderMapper
{
	/**
	 * 创建Order对象
	 *
	 * @param order
	 * @return
	 */
	int createOrder (final Order order);

	/**
	 * 查询所有数据
	 *
	 * @return
	 */
	List<Order> queryAll ();
}

MyBatis编写XML文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.chown.pine.sharding.database.mapper.OrderMapper">

    <!--创建订单-->
    <insert id="createOrder" parameterType="Order">
        INSERT INTO t_order
          (order_id, user_id, userName, passWord, user_sex)
        VALUES
          (#{order_id}, #{user_id}, #{userName}, #{passWord}, #{userSex})
    </insert>

    <!--查询所有数据-->
    <select id="queryAll" resultType="Order">
        select * from t_order;
    </select>
</mapper>

单元测试编写:

package com.chown.pine.sharding;

import com.chown.pine.sharding.boot.BootstrapApplication;
import com.chown.pine.sharding.database.entity.Order;
import com.chown.pine.sharding.database.mapper.OrderMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 * <一句话功能简述> <功能详细描述>
 *
 * @author zping
 * @version 2018/11/23 0023
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@RunWith (SpringRunner.class)
@SpringBootTest (classes = BootstrapApplication.class)
public class BootstrapApplicationTest
{

	@Autowired
	protected OrderMapper orderMapper;

	/**
	 * 程序启动测试类
	 */
	@Test
	public void contentLoad ()
	{
		/*Order order = new Order ();
		order.setOrder_id (1000003l);
		order.setUser_id (1000003l);
		order.setNick_name ("zping");
		order.setPassWord ("12334");
		order.setUserName ("Pine Chown");
		order.setUserSex ("MAN");
		orderMapper.createOrder (order);*/

		List<Order> orders = orderMapper.queryAll ();

		System.out.println (orders);

	}
}

数据库创建SQL:

/*
Navicat MySQL Data Transfer

Source Server         : test01
Source Server Version : 50636
Source Host           : 192.168.0.11:21000
Source Database       : t_db_1

Target Server Type    : MYSQL
Target Server Version : 50636
File Encoding         : 65001

Date: 2018-12-06 16:29:55
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for t_order_0
-- ----------------------------
DROP TABLE IF EXISTS `t_order_0`;
CREATE TABLE `t_order_0` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  `order_id` varchar(32) DEFAULT NULL COMMENT '顺序编号',
  `user_id` varchar(32) DEFAULT NULL COMMENT '用户编号',
  `userName` varchar(32) DEFAULT NULL COMMENT '用户名',
  `passWord` varchar(32) DEFAULT NULL COMMENT '密码',
  `user_sex` varchar(32) DEFAULT NULL,
  `nick_name` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for t_order_1
-- ----------------------------
DROP TABLE IF EXISTS `t_order_1`;
CREATE TABLE `t_order_1` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  `order_id` varchar(32) DEFAULT NULL COMMENT '顺序编号',
  `user_id` varchar(32) DEFAULT NULL COMMENT '用户编号',
  `userName` varchar(32) DEFAULT NULL COMMENT '用户名',
  `passWord` varchar(32) DEFAULT NULL COMMENT '密码',
  `user_sex` varchar(32) DEFAULT NULL,
  `nick_name` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;

/*
Navicat MySQL Data Transfer

Source Server         : test02
Source Server Version : 50636
Source Host           : 192.168.0.11:21000
Source Database       : t_db_2

Target Server Type    : MYSQL
Target Server Version : 50636
File Encoding         : 65001

Date: 2018-12-06 16:30:02
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for t_order_0
-- ----------------------------
DROP TABLE IF EXISTS `t_order_0`;
CREATE TABLE `t_order_0` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  `order_id` varchar(32) DEFAULT NULL COMMENT '顺序编号',
  `user_id` varchar(32) DEFAULT NULL COMMENT '用户编号',
  `userName` varchar(32) DEFAULT NULL COMMENT '用户名',
  `passWord` varchar(32) DEFAULT NULL COMMENT '密码',
  `user_sex` varchar(32) DEFAULT NULL,
  `nick_name` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for t_order_1
-- ----------------------------
DROP TABLE IF EXISTS `t_order_1`;
CREATE TABLE `t_order_1` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  `order_id` varchar(32) DEFAULT NULL COMMENT '顺序编号',
  `user_id` varchar(32) DEFAULT NULL COMMENT '用户编号',
  `userName` varchar(32) DEFAULT NULL COMMENT '用户名',
  `passWord` varchar(32) DEFAULT NULL COMMENT '密码',
  `user_sex` varchar(32) DEFAULT NULL,
  `nick_name` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;

完成!!!
GitHub项目地址:https://github.com/thestar111/chown-sharding-jdbc
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/u012397222/article/details/84857335