1. 程式人生 > >Spring Boot 結合 Sharding-Jdbc做分庫分表示例

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
在這裡插入圖片描述