shardingsphere mybatisplus properties和yml配置实现

shardingsphere mybatisplus properties和yml配置实现

目录结构
shardingsphere mybatisplus properties和yml配置实现_第1张图片
model

package com.oujiong.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.Date;

/**
 * user表
 */
@TableName("user")
@Data
public class User {
    /**
     * 主键
     */
    private Long id;

    /**
     * 姓名
     */
    private String name;

    /**
     * 性别
     */
    private String sex;

    /**
     * 年龄
     */
    private Integer age;

    /**
     *
     */
    private Date createTime;

    /**
     *
     */
    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.extension.service.impl.ServiceImpl;
import com.oujiong.entity.User;
import com.oujiong.mapper.UserMapper;
import java.util.List;

/**
 * @Description: 用户相关接口
 *
 */
public interface UserService  {

    /**
     *  获取所有用户信息
     */
    List<User>  list();

    /**
     *  批量 保存用户信息
     * @param userVOList
     */
    String  insertForeach(List<User> userVOList);

}

seviceImp

package com.oujiong.service.impl;
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;

/**
 * @author xub
 * @Description: 用户实现类
 * @date 2019/8/8 上午9:13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public  List<User> list() {
        List<User> users =new ArrayList<>();
        User user = this.getById(102);
//        User user = userMapper.selectById(102);
        users.add(user);
//        List 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.insertForeach(userList);
        return "保存成功";
    }
}

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);
	}

}

mapper.xml


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 tab_user
  select>

  <insert id="insertForeach" parameterType="java.util.List" useGeneratedKeys="false">
    insert into tab_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/sharding_test_1?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.6.193:3306/sharding_test_2?characterEncoding=utf-8
spring.shardingsphere.datasource.slave0.username=root
spring.shardingsphere.datasource.slave0.password=MyNewPass4!

#数据分表规则
#指定所需分的表(spring.shardingsphere.sharding.tables.user注意user)
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

spring.shardingsphere.sharding.tables.user注意user与实体类、xml相对应

shardingsphere mybatisplus properties和yml配置实现_第2张图片

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




你可能感兴趣的:(数据库,shardingsphere,mybatisplus)