springboot+mybatis+shardingsphere3.1.0实现分表

一、配置pom依赖

  io.shardingsphere

sharding-jdbc-core

3.1.0

二、配置数据库源(连接数据库的配置可以在yam文件,properties文件)

static final String MAPPER_LOCATION = "classpath*:/loan/mapping/*.xml";

@Bean(name = "firstDataSource")

    @Primary //必须加此注解,不然报错,下一个类则不需要添加

    @ConfigurationProperties(prefix = "spring.datasource")

    public DataSource firstDataSource() {

        return new DruidDataSource();

    }

    @Bean(name = "dataSource")

public DataSource shardingRule(@Qualifier("firstDataSource") DataSource dataSource) throws SQLException {

Map dataSourceMap = new HashMap<>();

dataSourceMap.put("ds0", dataSource);

// 配置Order表规则

TableRuleConfiguration accountTableRuleConfig = new TableRuleConfiguration();

accountTableRuleConfig.setLogicTable("order_list");

accountTableRuleConfig.setActualDataNodes("ds0.order_list${0..4}");

// 配置分表策略

accountTableRuleConfig.setTableShardingStrategyConfig(

new InlineShardingStrategyConfiguration("userId", "order_list${userId% 4}"));

ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();

shardingRuleConfig.getTableRuleConfigs().add(accountTableRuleConfig);

// 获取数据源对象

return ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfig, new ConcurrentHashMap(),

   new Properties());

}

@Bean

public SqlSessionFactory firstSqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {

        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();

        bean.setDataSource(dataSource);

        //添加XML目录

        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        try {

            bean.setMapperLocations(resolver.getResources(MAPPER_LOCATION));

            return bean.getObject();

        } catch (Exception e) {

            e.printStackTrace();

            throw new RuntimeException(e);

        }

    }

@Bean

    public SqlSessionTemplate firstSqlSessionTemplate(@Qualifier("firstSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {

        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory); // 使用上面配置的Factory

        return template;

    }

你可能感兴趣的:(springboot+mybatis+shardingsphere3.1.0实现分表)