目录
一、MyBatis-Plus简介
1、简介
2、特性
3、支持数据库
4、框架结构
5、代码及文档地址
二、入门案例
1、创建数据库及表
a>创建表
b>添加数据
3、创建Spring Boot工程
a>初始化工程
b>引入依赖
4、编写代码
a>配置application.yml
b>启动类
c>添加实体
d>添加mapper
e>测试
f>添加日志
三、基本CRUD
1、BaseMapper
2、插入
3、删除
a>通过id删除记录
b>通过id批量删除记录
c>通过map条件删除记录
4、修改
5、查询
b>根据多个id查询多个用户信息
c>通过map条件查询用户信息
d>查询所有数据
6、自定义功能
结果:
7、通用Service
a>IService
b>创建Service接口和实现类
c>测试查询记录数
d>测试批量插入
四、常用注解
1、@TableName
a>问题
b>通过@TableName解决问题
c>通过全局配置解决问题
2、@TableId
@TableId的value属性
@TableId的type属性
e>雪花算法
3、@TableField
a>情况1
b>情况2
4、@TableLogic
a>逻辑删除
b>实现逻辑删除
五、条件构造器和常用接口
1、wapper介绍
e>例5:组装select子句
2、QueryWrapper
a>例1:组装查询条件
b>例2:组装排序条件
c>例3:组装删除条件
d>例4:条件的优先级
e>例5:组装select子句
f>例6:实现子查询
3、UpdateWrapper
4、condition
5、LambdaQueryWrapper
6、LambdaUpdateWrapper
六、插件
1、分页插件
a>添加配置类
b>测试
2、xml自定义分页
a>UserMapper中定义接口方法
b>UserMapper.xml中编写SQL
c>测试
3、乐观锁
a>场景
b>乐观锁与悲观锁
c>模拟修改冲突
d>乐观锁实现流程
七、通用枚举
a>数据库表添加字段sex
b>创建通用枚举类型
c>配置扫描通用枚举
d>测试
八、代码生成器
1、引入依赖
2、快速生成
九、多数据源
1、创建数据库及表
2、引入依赖
3、配置多数据源
4、创建用户service
5、创建商品service
6、测试
十、MyBatisX插件
1.生成代码
1.安装
2. 快速生成CRUD
CREATE DATABASE `mybatis_plus` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;
use `mybatis_plus`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL COMMENT '主键ID',
`name` varchar(30) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`email` varchar(50) DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');
使用 Spring Initializr 快速初始化一个 Spring Boot 工程
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-test
test
com.baomidou
mybatis-plus-boot-starter
3.5.1
org.projectlombok
lombok
true
mysql
mysql-connector-java
runtime
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC
username: root
password: woaini520
@SpringBootApplication
//扫描mapper接口所在的包
@MapperScan("com.javastudy.mybatisplus.mapper")
public class Mybatisplus01Application {
public static void main(String[] args) {
SpringApplication.run(Mybatisplus01Application.class, args);
}
}
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
@Repository
public interface UserMapper extends BaseMapper {
}
@SpringBootTest
public class MybatisPlusTest {
@Autowired
UserMapper mapper;
@Test
public void testSelectList(){
//通过条件构造器查询一个list集合,若没有条件,可以设置null
List users = mapper.selectList(null);
for (User user : users) {
System.out.println(user);
}
}
}
结果
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
@Test
/**
* 新增用户信息
*/
public void testInsert() {
//通过条件构造器查询一个list集合,若没有条件,可以设置null
User user = new User();
user.setName("张选宁");
user.setAge(19);
user.setEmail("[email protected]");
System.out.println("id:" + user.getId());
//INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
int insert = mapper.insert(user);
System.out.println("产生条数:" + insert);
System.out.println("id:" + user.getId());
}
@Test
public void testDeleteById() {
//通过id删除用户信息
// DELETE FROM user WHERE id=?
int result = mapper.deleteById(1475754982694199298L);
System.out.println("受影响行数:" + result);
}
@Test
public void testDeleteBatchIds(){
//通过多个id批量删除
//DELETE FROM user WHERE id IN ( ? , ? , ? )
List idList = Arrays.asList(1L, 2L, 3L);
int result = mapper.deleteBatchIds(idList);
System.out.println("受影响行数:"+result);
}
@Test
public void testDeleteByMap() {
//根据map集合中所设置的条件删除记录
//DELETE FROM user WHERE name = ? AND age = ?
Map map = new HashMap<>();
map.put("age", 23);
map.put("name", "张三");
int result = mapper.deleteByMap(map);
System.out.println("受影响行数:" + result);
}
@Test
public void testUpdateById(){
User user = new User(4L, "admin", 22, null);
//UPDATE user SET name=?, age=? WHERE id=?
int result = mapper.updateById(user);
}
a>根据id查询用户信息
@Test
public void testSelectBatchIds(){
//根据多个id查询多个用户信息
//SELECT id,name,age,email FROM user WHERE id IN ( ? , ? )
List idList = Arrays.asList(4L, 5L);
List list = mapper.selectBatchIds(idList);
list.forEach(System.out::println);
}
@Test
public void testSelectById(){
//根据id查询用户信息
//SELECT id,name,age,email FROM user WHERE id=?
User user = mapper.selectById(4L);
System.out.println(user);
}
@Test
public void testSelectByMap(){
//通过map条件查询用户信息
//SELECT id,name,age,email FROM user WHERE name = ? AND age = ?
Map map = new HashMap<>();
map.put("age", 22);
map.put("name", "admin");
List list = mapper.selectByMap(map);
list.forEach(System.out::println);
}
@Test
public void testSelectList(){
//查询所有用户信息
//SELECT id,name,age,email FROM user
List list = mapper.selectList(null);
list.forEach(System.out::println);
}
/**
* 根据id查询用户信息为Mapper集合
* @param id
* @return
*/
Map selectMapById(Long id);
@Test
/**
* 测试查询功能
*/
public void testSelect() {
Map map = mapper.selectMapById(1L);
System.out.println(map);
}
{name=张选宁, id=1, age=19, [email protected]}
public interface UserService extends IService {
}
@Service
public class UserServiceImpl extends ServiceImpl implements UserService {
}
@Test
public void testGetCount(){
//SELECT COUNT( * ) FROM user
long count = service.count();
System.out.println("总数量:"+count);
}
@Test
public void testInsertMore(){
List users = new ArrayList<>();
for (int i = 0; i < 10; i++) {
User user = new User();
user.setName("zxn"+i);
user.setAge(20+i);
user.setEmail("[email protected]");
users.add(user);
}
//INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
boolean b = service.saveBatch(users);
System.out.println(b);
}
当表名和实体类的类名不一致时,会出现以下问题
@Data
//设置实体类所对应的表名
@TableName("t_user")
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#设置mybatisplus的全局配置,设置实体类所对应表的统一前缀
global-config:
db-config:
table-prefix: t_
当作为主键的字段的名字不为id时,加入@TableId将其变为主键
//将属性所对应的字段指定为主键
@TableId
private Long id;
@TableId(value = "uid")
private Long id;
默认的为雪花算法
值
|
描述
|
IdType.ASSIGN_ID (默
认)
|
基于雪花算法的策略生成数据 id ,与数据库 id 是否设置自增无关
|
IdType.AUTO
|
使用数据库的自增策略,注意,该类型请确保数据库设置了 id 自增,
否则无效
|
改变为主键自增
//@TableId注解的type属性设置主键生成策略
@TableId(value = "uid",type = IdType.AUTO)
private Long id;
注意:只在数据库里面将字段设置为主键自增是没有效果的
当我们自己设置了id的值,insert添加数据到表中,是不会用雪花算法的
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#设置mybatisplus的全局配置,设置实体类所对应表的统一前缀
global-config:
db-config:
table-prefix: t_
#设置统一的主键生成策略
id-type: auto
②优点:整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞,并且效率较高。
//指定属性所对应的字段名
@TableField("user_name")
private String name;
在表中添加字段is_delete
实体类中添加属性,并加上@TableLogic注解
@TableLogic
private int isDelete;
之后的删除操作变为
UPDATE t_user SET is_delete=1 WHERE uid IN ( ? , ? , ? ) AND is_delete=0
原本
删除之后变为
SELECT uid AS id,user_name AS name,age,email,is_delete FROM t_user WHERE is_delete=0
便查不到is_delete为1的数据了
@Test
public void test01(){
QueryWrapper wrapper = new QueryWrapper<>();
QueryWrapper queryWrapper = wrapper.like("user_name", "宁").
between("age", 15, 30).isNotNull("email");
//SELECT uid AS id,user_name AS name,age,email,is_delete FROM t_user
// WHERE is_delete=0 AND (user_name LIKE ? AND age BETWEEN ? AND ? AND email IS NOT NULL)
List users = mapper.selectList(queryWrapper);
for (User user : users) {
System.out.println(user);
}
}
@Test
public void test02(){
//查询用户信息按照年龄的降序排序,若年龄相同,则按照id升序排序
QueryWrapper wrapper = new QueryWrapper<>();
QueryWrapper userQueryWrapper = wrapper.orderByDesc("age").orderByAsc("uid");
//SELECT uid AS id,user_name AS name,age,email,is_delete FROM t_user
// WHERE is_delete=0 ORDER BY age DESC,uid ASC
List users = mapper.selectList(userQueryWrapper);
for (User user : users) {
System.out.println(user);
}
}
@Test
public void test03(){
//删除邮箱的地址为null的用户信息
QueryWrapper wrapper = new QueryWrapper<>();
QueryWrapper queryWrapper = wrapper.isNull("email");
//UPDATE t_user SET is_delete=1 WHERE is_delete=0 AND (email IS NULL)
int delete = mapper.delete(queryWrapper);
System.out.println("删除记录数为:"+delete);
}
@Test
public void test04(){
//将(年龄大于20并且用户名中包含有a)或邮箱为null的用户信息修改
UpdateWrapper wrapper = new UpdateWrapper<>();
UpdateWrapper updateWrapper = wrapper.gt("age", 20).like("user_name", "宁")
.or().isNull("email");
User user = new User();
user.setName("小宁子");
user.setAge(18);
//UPDATE t_user SET user_name=?, age=? WHERE is_delete=0 AND (age > ? AND user_name LIKE ? OR email IS NULL)
int update = mapper.update(user, updateWrapper);
System.out.println("更新了条数:"+update);
}
@Test
public void test05(){
//将用户名中包含有"宁"并且(年龄大于20或邮箱为null)的用户信息修改
UpdateWrapper wrapper = new UpdateWrapper<>();
UpdateWrapper updateWrapper = wrapper.like("user_name", "宁").
and(i -> i.gt("age", 20).or().isNull("email"));
User user = new User();
user.setName("张选宁");
user.setAge(20);
//UPDATE t_user SET user_name=?, age=?
// WHERE is_delete=0 AND (user_name LIKE ? AND (age > ? OR email IS NULL))
int update = mapper.update(user, updateWrapper);
System.out.println("更新了条数:"+update);
}
@Test
public void test06(){
//查询用户的用户名、年龄、邮箱信息
QueryWrapper wrapper = new QueryWrapper<>();
QueryWrapper select = wrapper.select("user_name", "age", "email");
List
@Test
public void test07(){
//查询id小于等于100的用户信息
QueryWrapper wrapper = new QueryWrapper<>();
QueryWrapper queryWrapper = wrapper.inSql("uid", "select uid from t_user where uid<=100");
//SELECT uid AS id,user_name AS name,age,email,is_delete FROM t_user
// WHERE is_delete=0 AND (uid IN (select uid from t_user where uid<=100))
List users = mapper.selectList(queryWrapper);
for (User user : users) {
System.out.println(user);
}
}
@Test
public void test08(){
//将用户名中包含有"宁"并且(年龄大于20或邮箱为null)的用户信息修改
UpdateWrapper wrapper = new UpdateWrapper<>();
UpdateWrapper updateWrapper = wrapper.like("user_name", "宁").
and(i -> i.gt("age", 20).or().isNull("email"));
UpdateWrapper updateWrapper1 = updateWrapper.set("user_name", "刘子").set("age", 19);
//UPDATE t_user SET user_name=?,age=?
// WHERE is_delete=0 AND (user_name LIKE ? AND (age > ? OR email IS NULL))
int update = mapper.update(null,updateWrapper1);
System.out.println("更新了条数:"+update);
}
模拟开发中组装条件的情况
@Test
public void test09(){
String username="";
Integer ageBegin=20;
Integer ageEnd=30;
QueryWrapper wrapper = new QueryWrapper<>();
if(StringUtils.isNotBlank(username)){
wrapper.like("user_name", username);
}
if(ageBegin!=null){
wrapper.ge("age",ageBegin);
}
if(ageEnd!=null){
wrapper.le("age",ageEnd);
}
//SELECT uid AS id,user_name AS name,age,email,is_delete FROM t_user
// WHERE is_delete=0 AND (age >= ? AND age <= ?)
List
使用condition组装条件 ----------->推荐
@Test
public void test10(){
String username="";
Integer ageBegin=20;
Integer ageEnd=30;
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.like(StringUtils.isNotBlank(username),"user_name",username);
wrapper.ge(ageBegin!=null,"age",ageBegin);
wrapper.le(ageEnd!=null,"age",ageEnd);
List users = mapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
@Test
public void test11(){
String username="";
Integer ageBegin=20;
Integer ageEnd=30;
LambdaQueryWrapper userLambdaQueryWrapper = new LambdaQueryWrapper<>();
userLambdaQueryWrapper.like(StringUtils.isNotBlank(username),User::getName,username);
userLambdaQueryWrapper.ge(ageBegin!=null,User::getAge,ageBegin);
userLambdaQueryWrapper.ge(ageEnd!=null,User::getAge,ageEnd);
List users = mapper.selectList(userLambdaQueryWrapper);
for (User user : users) {
System.out.println(user);
}
}
@Test
public void test12(){
//将用户名中包含有"宁"并且(年龄大于20或邮箱为null)的用户信息修改
LambdaUpdateWrapper userLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
LambdaUpdateWrapper updateWrapper = userLambdaUpdateWrapper.like(User::getName, "刘").
and(i -> i.gt(User::getAge, 20).or().isNull(User::getEmail));
LambdaUpdateWrapper updateWrapper1 = updateWrapper.set(User::getName, "刘子").set(User::getAge, 21);
//UPDATE t_user SET user_name=?,age=?
// WHERE is_delete=0 AND (user_name LIKE ? AND (age > ? OR email IS NULL))
int update = mapper.update(null,updateWrapper1);
System.out.println("更新了条数:"+update);
}
@Configuration
//扫描mapper接口所在的包
@MapperScan("com.javastudy.mybatisplus.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
@Test
public void testPage(){
Page userPage = new Page<>(3,3);
//SELECT uid AS id,user_name AS name,age,email,is_delete FROM t_user WHERE is_delete=0 LIMIT ?,?
Page userPage1 = mapper.selectPage(userPage, null);
System.out.println(userPage1.getRecords());
//[User(id=7, name=小宁子, age=18, [email protected], isDelete=0),
// User(id=8, name=刘子, age=19, [email protected], isDelete=0),
// User(id=9, name=刘子, age=21, email=null, isDelete=0)]
System.out.println(userPage1.getPages());//4
System.out.println(userPage1.getTotal());//10
System.out.println(userPage1.hasNext());//true
System.out.println(userPage1.hasPrevious());//true
}
Page selectVo(@Param("page") Page page,@Param("age") Integer age);
@Test
public void testVo(){
Page userPage = new Page<>(1,3);
Page userPage1 = mapper.selectVo(userPage, 20);
List records = userPage1.getRecords();
System.out.println(records);
}
结果
Preparing: select * from t_user where age>? LIMIT ?
==> Parameters: 20(Integer), 3(Long)
<== Columns: uid, user_name, age, email, is_delete
<== Row: 3, 乔浪, 26, [email protected], 0
<== Row: 4, 李四, 21, [email protected], 0
<== Row: 5, Billie, 24, [email protected], 0
<== Total: 3
CREATE TABLE t_product(id BIGINT ( 20 ) NOT NULL COMMENT ' 主键 ID' ,NAME VARCHAR ( 30 ) NULL DEFAULT NULL COMMENT ' 商品名称 ' ,price INT ( 11 ) DEFAULT 0 COMMENT ' 价格 ' ,VERSION INT ( 11 ) DEFAULT 0 COMMENT ' 乐观锁版本号 ' ,PRIMARY KEY (id));
添加数据
INSERT INTO t_product (id, NAME, price) VALUES (1, '外星人笔记本', 100);
添加实体
@Data
public class Product {
private Long id;
private String name;
private Integer price;
private Integer version;
}
添加mapper
@Repository
public interface ProductMapper extends BaseMapper {
}
测试
@Test
public void test11(){
//小李查询商品价格
Product productLi = productMapper.selectById(1);
System.out.println("小李查询到的商品:"+productLi);
//小王查询到的价格
Product productWang = productMapper.selectById(1);
System.out.println("小王查询到的商品:"+productWang);
//小李将商品价格加50
productLi.setPrice(productLi.getPrice()+50);
productMapper.updateById(productLi);
//小王将商品价格减30
productWang.setPrice(productWang.getPrice()-30);
productMapper.updateById(productWang);
//老板查询价格
Product productBoos = productMapper.selectById(1);
System.out.println("老板查询到的商品:"+productBoos);
}
最后产生的结果
老板查询到的商品:Product(id=1, name=外星人笔记本, price=70, version=0)
@Data
public class Product {
private Long id;
private String name;
private Integer price;
@Version
private Integer version;
}
@Configuration
//扫描mapper接口所在的包
@MapperScan("com.javastudy.mybatisplus.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//添加分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
//添加乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
@Test
public void test11(){
//小李查询商品价格
Product productLi = productMapper.selectById(1);
System.out.println("小李查询到的商品:"+productLi);
//小王查询到的价格
Product productWang = productMapper.selectById(1);
System.out.println("小王查询到的商品:"+productWang);
//小李将商品价格加50
productLi.setPrice(productLi.getPrice()+50);
productMapper.updateById(productLi);
//小王将商品价格减30
productWang.setPrice(productWang.getPrice()-30);
int result = productMapper.updateById(productWang);
while(result==0){
//操作失败,重试
Product productWang2 = productMapper.selectById(1);
System.out.println("小王查询到的商品:"+productWang2);
productWang2.setPrice(productWang2.getPrice()-30);
result = productMapper.updateById(productWang2);
}
//老板查询价格
Product productBoos = productMapper.selectById(1);
System.out.println("老板查询到的商品:"+productBoos);
}
@Getter
public enum SexEnums {
Male(0,"男"),
Female(1,"女");
@EnumValue //将注解所表示的属性值存储到数据库中
private Integer sex;
private String sexName;
SexEnums(Integer sex, String sexName) {
this.sex = sex;
this.sexName = sexName;
}
}
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#设置mybatisplus的全局配置,设置实体类所对应表的统一前缀
global-config:
db-config:
table-prefix: t_
#设置统一的主键生成策略
id-type: auto
#配置类型别名所对应的包
type-aliases-package: com.javastudy.mybatisplus.entity
#扫描通用枚举的包
type-enums-package: com.javastudy.mybatisplus.enums
@SpringBootTest
public class MyBatisPlusEnumTest {
@Autowired
UserMapper userMapper;
@Test
public void test01(){
User user = new User();
user.setName("薛子");
user.setAge(18);
user.setEmail("[email protected]");
user.setSex(SexEnums.Male);
int insert = userMapper.insert(user);
System.out.println("result:"+insert);
}
}
com.baomidou
mybatis-plus-generator
3.5.1
org.freemarker
freemarker
2.3.31
public class FastAutoGeneratorTest {
public static void main(String[] args) {
FastAutoGenerator.create("jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC",
"root", "woaini520")
.globalConfig(builder -> {
builder.author("Chooker") // 设置作者
//.enableSwagger() // 开启 swagger 模式
.fileOverride() // 覆盖已生成文件
.outputDir("D://mybatis_plus"); // 指定输出目录
})
.packageConfig(builder -> {
builder.parent("com.javastudy") // 设置父包名
.moduleName("mybatisplus") // 设置父包模块名
.pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D://mybatis_plus"));
// 设置mapperXml生成路径
})
.strategyConfig(builder -> {
builder.addInclude("t_user") // 设置需要生成的表名
.addTablePrefix("t_", "c_"); // 设置过滤表前缀
})
.templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.execute();
}
}
生成的结果
CREATE DATABASE `mybatis_plus_1` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ ;use `mybatis_plus_1`;CREATE TABLE product(id BIGINT ( 20 ) NOT NULL COMMENT ' 主键 ID' ,name VARCHAR ( 30 ) NULL DEFAULT NULL COMMENT ' 商品名称 ' ,price INT ( 11 ) DEFAULT 0 COMMENT ' 价格 ' ,version INT ( 11 ) DEFAULT 0 COMMENT ' 乐观锁版本号 ' ,PRIMARY KEY (id));
INSERT INTO product (id, NAME, price) VALUES ( 1 , ' 外星人笔记本 ' , 100 );
删除mybatis_plus库的product表
use mybatis_plus;DROP TABLE IF EXISTS product;
com.baomidou
dynamic-datasource-spring-boot-starter
3.5.0
spring:
datasource:
dynamic:
primary: master
strict: false
datasource:
master:
url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: woaini520
slave_1:
url: jdbc:mysql://localhost:3306/mybatis_plus_1?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: woaini520
public interface UserService extends IService {
}
@Service
@DS("master")
public class UserServiceImpl extends ServiceImpl implements UserService {
}
public interface ProductService extends IService {
}
@Service
@DS("slave_1")
public class ProductServiceImpl extends ServiceImpl implements ProductService {
}
@SpringBootTest
class Mybatisplus02ApplicationTests {
@Autowired
UserService userService;
@Autowired
ProductService productService;
@Test
public void test01(){
User byId = userService.getById(1L);
System.out.println(byId);
Product byId1 = productService.getById(1L);
System.out.println(byId1);
}
}
下载安装使用,重启
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC
username: root
password: woaini520
配置Mysql
1.先写出关键字
2.选择