Sharding JDBC integrates mybatis plus to realize the solution of sub database and sub table

Time:2021-10-16

Project address:

  • Github
  • Gitee

Official documents:

  • Sharding-JDBC
  • Mybatis-Plus

1、 Run test

  • Step 1: create two new databases:seal_sharding、seal_sharding1
  • Step 2: import SQL files in DB directory respectively
  • Step 3: open the project and configure environment variablesMYSQL_HOST、MYSQL_PORTAnd user name and password
  • Step 4: run test files (under test package)

2、 Acquisition of tenant ID

Modify mybaitsplusconfig.java under the config package to obtain the tenant ID of the currently logged in user. Here, 1 is written by default

@Override
public Expression getTenantId() {
    try {
        //Get the tenant ID of the currently logged in user
        String tenantId = "1";
        if (!StrUtil.isEmpty(tenantId)) {
            return new LongValue(tenantId);
        }
        Throw new exception (retback. Errorjson (4001, "the tenant does not exist");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new LongValue(-1L);
}

3、 Database and table strategy

  • Sub Library: according to table fieldsTenant ID (tenant_id)Module 2 (odd even number) for library division
  • Split table: according to table fieldsidGo to hascode modulo 2 (odd even number) to distribute the table, and the distributed primary key adoptsSnow flake algorithm (snowflake)See sharding JDBC for details

3、 Table only, no database

This project implements database and table splitting for two data sources. If only table and no database are divided, only one data source needs to be added

4、 Implementation considerations

  • Sharding JDBC adopts3.xedition
  • Mybaitsplus configuration needs to be replicated
  • Exclude automatic data source loading
@SpringBootApplication(exclude = {DruidDataSourceAutoConfigure.class, 
DataSourceAutoConfiguration.class})

Attachment: mybatis plus multiple data sources

If you do not use sharding JDBC, you need toMultiple data sources, can be usedMybaits plus multi data source scheme, see the official documents for details. I’ll put it laterSample projectShare with you, please look forward to it. Can add me to communicate with each other.

Open source is not easy, and use and cherish!

Sponsor authors and communicate with each other

Sharding JDBC integrates mybatis plus to realize the solution of sub database and sub table

Sharding JDBC integrates mybatis plus to realize the solution of sub database and sub table

Please note: my technology sharing » sharding JDBC integrates mybatis plus to realize sub database and sub table solution