shardingsphere mybatisplus properties和yml配置实现
目录结构
model
package com.oujiong.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
/**
* user表
*/
@TableName("user")
@Data
public class User {
/**
* 主键
*/
private Long id;
/**
* 姓名
*/
private String name;
/**
* 性别
*/
private String sex;
/**
* 年龄
*/
private Integer age;
/**
*
*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
/**
*
*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
/**
* 是否删除 1删除 0未删除
*/
private Integer status;
public User(Long id, String name, String sex, Integer age) {
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
}
}
mapper
package com.oujiong.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.oujiong.entity.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @Description: 用户mapper
*/
@Mapper
public interface UserMapper extends BaseMapper<User> {
/**
* 批量插入
*
* @param list 插入集合
* @return 插入数量
*/
int insertForeach(List<User> list);
/**
* 获取所有用户
*/
List<User> selectAll();
}
servie
package com.oujiong.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.oujiong.entity.User;
import com.oujiong.mapper.UserMapper;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
/**
* @Description: 用户相关接口
*
*/
public interface UserService {
/**
* 获取所有用户信息
*/
List<User> list();
/**
* 批量 保存用户信息
*
* @param userVOList
*/
String insertForeach(List<User> userVOList);
IPage<User> pageUser(Integer currentPage, Integer pageSize);
}
seviceImp
package com.oujiong.service.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oujiong.entity.User;
import com.oujiong.mapper.UserMapper;
import com.oujiong.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @Description: 用户实现类
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> list() {
// List<User> users =new ArrayList<>();
// users= this.lambdaQuery().orderByAsc(User::getAge).list();
// User user = userMapper.selectById(102);
// users.add(user);
List<User> users = userMapper.selectAll();
return users;
}
@Override
public String insertForeach(List<User> userList) {
for (User user : userList) {
user.setCreateTime(new Date());
user.setUpdateTime(new Date());
user.setStatus(0);
userMapper.insert(user);
}
// //批量插入数据
// userMapper.insertForeach(userList);
return "保存成功";
}
@Override
public IPage<User> pageUser(Integer currentPage, Integer pageSize){
IPage<User> page =new Page<>();
page.setCurrent(currentPage);
page.setSize(pageSize);
IPage<User> users= this.lambdaQuery().orderByAsc(User::getAge).page(page);
return users;
}
}
Application
package com.oujiong;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @Description: 启动类
*
* @author xub
* @date 2019/10/08 下午6:33
*/
@MapperScan("com.oujiong.mapper.**")
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
分页配置
package com.oujiong.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
mapper.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.oujiong.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.oujiong.entity.User">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="sex" jdbcType="VARCHAR" property="sex" />
<result column="age" jdbcType="INTEGER" property="age" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
<result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
<result column="status" jdbcType="INTEGER" property="status" />
</resultMap>
<sql id="Base_Column_List">
id, name, sex, age, create_time, update_time, status
</sql>
<select id="selectAll" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
</select>
<insert id="insertForeach" parameterType="java.util.List" useGeneratedKeys="false">
insert into user (id, name, sex,
age, create_time, update_time,
status)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.id,jdbcType=BIGINT}, #{item.name,jdbcType=VARCHAR}, #{item.sex,jdbcType=VARCHAR},
#{item.age,jdbcType=INTEGER}, #{item.createTime,jdbcType=TIMESTAMP}, #{item.updateTime,jdbcType=TIMESTAMP},
#{item.status,jdbcType=INTEGER})
</foreach>
</insert>
</mapper>
properties和yml配置 目录结构和java文件配置都一致
properties
server.port=8088
#指定mybatis信息
mybatis.config-location=classpath:mybatis-config.xml
## 一个实体类对应多张表,覆盖
spring.main.allow-bean-definition-overriding=true
#数据库
spring.shardingsphere.datasource.names=master0,slave0
spring.shardingsphere.datasource.master0.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.master0.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.master0.url=jdbc:mysql://139.155.6.193:3306/test?characterEncoding=utf-8
spring.shardingsphere.datasource.master0.username=root
spring.shardingsphere.datasource.master0.password=MyNewPass4!
spring.shardingsphere.datasource.slave0.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.slave0.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.slave0.url=jdbc:mysql://139.155.237.188:3306/test?characterEncoding=utf-8
spring.shardingsphere.datasource.slave0.username=root
spring.shardingsphere.datasource.slave0.password=MyNewPass4!
#数据分表规则
#指定所需分的表
spring.shardingsphere.sharding.tables.user.actual-data-nodes=master0.tab_user$->{0..1}
#指定主键
spring.shardingsphere.sharding.tables.user.table-strategy.inline.sharding-column=id
#分表规则为主键除以2取模
spring.shardingsphere.sharding.tables.user.table-strategy.inline.algorithm-expression=tab_user$->{id % 2}
# 读写分离
spring.shardingsphere.masterslave.load-balance-algorithm-type=round_robin
spring.shardingsphere.masterslave.name=ms
#这里配置读写分离的时候一定要记得添加主库的数据源名称 这里为master0
spring.shardingsphere.sharding.master-slave-rules.master0.master-data-source-name=master0
spring.shardingsphere.sharding.master-slave-rules.master0.slave-data-source-names=slave0
#spring.shardingsphere.sharding.binding-tables[0]=user
#spring.shardingsphere.mode.type=Memory
#spring.shardingsphere.mode.repository.type=File
#spring.shardingsphere.mode.overwrite=true
#打印sql
spring.shardingsphere.props.sql.show=true
# mybatis-plus
mybatis-plus.mapper-locations=classpath:mapper/**/*.xml
mybatis-plus.type-aliases-package=com.oujiong.entity
#打印带参数sql
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
spring.shardingsphere.sharding.tables.user注意user与实体类、xml相对应
yml
#服务器设置
server:
port: 8090
spring:
# 文件上传需要
main:
allow-bean-definition-overriding: true
shardingsphere:
# 数据库名称
datasource:
names: master0,slave0
master0:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://139.155.6.193:3306/sharding_test_1?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
username: root
password: MyNewPass4!
slave0:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://139.155.6.193:3306/sharding_test_2?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
username: root
password: MyNewPass4!
# 配置主从规则
# ====================== ↓↓↓↓↓↓ 读写分离配置 ↓↓↓↓↓↓ ======================
master-slave-rules:
master0:
# 主库
masterDataSourceName: master0
# 从库
slaveDataSourceNames:
- slave0
# 从库查询数据的负载均衡算法 目前有2种算法 round_robin(轮询)和 random(随机)
# 算法接口 org.apache.shardingsphere.spi.masterslave.MasterSlaveLoadBalanceAlgorithm
# 实现类 RandomMasterSlaveLoadBalanceAlgorithm 和 RoundRobinMasterSlaveLoadBalanceAlgorithm
loadBalanceAlgorithmType: ROUND_ROBIN
# 配置分片规则
sharding:
tables:
user:
logicTable: tab_user
actual-data-nodes: master0.tab_user$->{0..1}
# database-strategy:
# inline:
# sharding-column: id
# algorithm-expression: master0
table-strategy:
inline:
sharding-column: id
algorithm-expression: tab_user$->{id % 2}
props:
sql:
show: true # 打印SQL
pom依赖
<properties>
<java.version>1.8</java.version>
<mybatis-spring-boot>2.0.1</mybatis-spring-boot>
<druid>1.1.16</druid>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.mybatis.spring.boot</groupId>-->
<!-- <artifactId>mybatis-spring-boot-starter</artifactId>-->
<!-- <version>${mybatis-spring-boot}</version>-->
<!-- </dependency>-->
<!--mybatis驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid}</version>
</dependency>
<!--shardingsphere最新版本-->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.0.0-RC1</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-namespace</artifactId>
<version>4.0.0-RC1</version>
</dependency>
<!--lombok实体工具-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
</dependencies>