从零玩转ShardingSphere分库分表 (建立JDBC环境)
创建表
CREATE TABLE `t_order` (
`tid` bigint(20) NOT NULL,
`tname` varchar(255) DEFAULT NULL,
`goods_id` bigint(20) DEFAULT NULL,
`tstatus` varchar(255) DEFAULT NULL,
PRIMARY KEY (`tid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
建立Mybatis-plus工程
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.22</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.0.0-beta</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
创建实体类
@Data
@TableName("t_order")
public class Order {
private Long tid;
private String tname;
private Long goodsId;
private String tstatus;
}
创建Mapper
public interface OrderMapper extends BaseMapper<Order> {
}
添加Mapper扫描
配置分库分表
# 应用名称
spring.application.name=Sharding
server.port=9630
# 配置真实数据源
spring.shardingsphere.datasource.names=db0
# 配置第一个数据源
spring.shardingsphere.datasource.db0.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.db0.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.db0.url=jdbc:mysql://127.0.0.1:3308/xxxxxx?serverTimezone=GMT%2B8&characterEncoding=utf-8
spring.shardingsphere.datasource.db0.username=root
spring.shardingsphere.datasource.db0.password=xxxxx
# plush 打印
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
spring.shardingsphere.props.sql-show=true
测试是否可以操作
@SpringBootTest
@RunWith(SpringRunner.class)
class ShardingApplicationTests {
@Autowired
private OrderMapper orderMapper;
@Test
void contextLoads () {
for (int i = 0; i < 10; i++) {
Order order = new Order();
order.setTid(Long.valueOf(i));
order.setTname("订单" + i);
order.setGoodsId(Long.valueOf("" + (1000 + i)));
order.setTstatus("1");
System.out.println(order);
orderMapper.insert(order);
}
}
}
结果
数据库查看是否新增数据存在
评论区