1. 创建项目
创建一个名为mybatis-plus-demo的项目,使用Maven+JDK17。不会的请看 IntelliJ IDEA快速创建Spring Boot项目,最终项目结构,如下图。
2. 编写代码
根据最终项目结构,从下往上依次列出各个文件的代码。
2.1 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>mybatis-plus-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!-- 为Spring Boot项目提供一系列默认的配置和依赖管理-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.2</version>
<relativePath/>
</parent>
<dependencies>
<!-- Spring Boot核心依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- Spring Boot单元测试和集成测试的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Boot构建Web应用程序的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mysql驱动-->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<!-- mybatis-plus核心依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>3.5.7</version>
</dependency>
<!-- 动态数据源依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot3-starter</artifactId>
<version>4.3.1</version>
</dependency>
</dependencies>
</project>
2.2 application.properties
# 默认的数据源
spring.datasource.dynamic.primary=master
# 严格匹配数据源,默认false
spring.datasource.dynamic.strict=false
# 取消druid自动配置
spring.autoconfigure.exclude=com.alibaba.druid.spring.boot3.autoconfigure.DruidDataSourceAutoConfigure
# 主库
spring.datasource.dynamic.datasource.master.url=jdbc:mysql://127.0.0.1:33066/test
spring.datasource.dynamic.datasource.master.username=root
spring.datasource.dynamic.datasource.master.password=123456
# 从库
spring.datasource.dynamic.datasource.slave.url=jdbc:mysql://127.0.0.1:33067/test
spring.datasource.dynamic.datasource.slave.username=root
spring.datasource.dynamic.datasource.slave.password=123456
#显示sql
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
2.3 mapper/UserMapperSlave.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="org.example.mapper.UserMapperSlave">
<select id="selectAllPage" parameterType="java.util.Map" resultType="java.util.Map">
select * from t_user_a
<where>
<if test="param.name != null and param.name != ''">
INSTR(CONCAT(IFNULL(name,'')),#{param.name})>0
</if>
</where>
</select>
</mapper>
2.4 org/example/Main.java
package org.example;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement // 启用事务管理
@MapperScan("org.example.mapper") // 扫描mapper
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
2.5 org/example/mapper/UserMapperSlave.java
注意@DS(“slave”)注解,与配置文件中数据源名称相对应
package org.example.mapper;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Param;
import org.example.entity.User;
import java.util.List;
import java.util.Map;
@DS("slave")
public interface UserMapperSlave extends BaseMapper<User> {
@MapKey("")
List<Map<String, Object>> selectAllPage(Page<?> page, @Param("param") Map<String, Object> param);
}
2.6 org/example/mapper/UserMapperMaster.java
package org.example.mapper;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.example.entity.User;
@DS("master")
public interface UserMapperMaster extends BaseMapper<User> {
}
2.7 org/example/entity/User.java
package org.example.entity;
import com.baomidou.mybatisplus.annotation.*;
import java.util.Date;
@TableName("t_user_a")
public class User {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
private String name;
private String phone;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
2.8 org/example/controller/UserController.java
package org.example.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.entity.User;
import org.example.mapper.UserMapperMaster;
import org.example.mapper.UserMapperSlave;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/UserController")
public class UserController {
@Autowired
private UserMapperMaster userMapperMaster;
@Autowired
private UserMapperSlave userMapperSlave;
@RequestMapping(value = "/insertMaster")
@ResponseBody
@Transactional
public Object insertMaster() {
for (int i = 0; i < 20; i++) {
User user = new User();
user.setName("张"+i);
user.setPhone(new Date().getTime()+"");
userMapperMaster.insert(user);
}
return "数据插入成功";
}
@RequestMapping(value = "/listAllMaster")
@ResponseBody
public Object listAllMaster() {
QueryWrapper<User> q = new QueryWrapper<>();
q.like("name", "张1");
List<User> list = userMapperMaster.selectList(q);
return list;
}
@RequestMapping(value = "/listAllSlave")
@ResponseBody
public Object listAllSlave() {
QueryWrapper<User> q = new QueryWrapper<>();
q.like("name", "张1");
List<User> list = userMapperSlave.selectList(q);
return list;
}
@RequestMapping(value = "/listPageSlave")
@ResponseBody
public Object listPageSlave() {
Page<?> page = new Page<>(1, 3);
Map<String, Object> param = new HashMap<>();
param.put("name", "张");
List<Map<String, Object>> list = userMapperSlave.selectAllPage(page, param);
return list;
}
}
2.9 org/example/conf/MyMetaObjectHandler.java
package org.example.conf;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
/*
MyBatis-Plus 提供了一个便捷的自动填充功能,用于在插入或更新数据时自动填充某些字段,如创建时间、更新时间等
*/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime", new Date(), metaObject);
this.setFieldValByName("updateTime", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime", new Date(), metaObject);
}
}
3.0 org/example/conf/MybatisPlusConfig.java
package org.example.conf;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/*
MyBatis-Plus 配置
*/
@Configuration
public class MybatisPlusConfig {
/**
* 添加分页插件
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
3. 测试
3.1 创建表
分别在两个数据库创建表t_user_a。
-- test.t_user_a definition
CREATE TABLE `t_user_a` (
`id` bigint(20) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`phone` varchar(255) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3.2 master插入数据
启动项目,然后访问:http://localhost:8080/UserController/insertMaster,可以看到master数据库已经插入成功。
3.3 slave查询数据
访问:http://localhost:8080/UserController/listAllSlave,可以看到从slave数据库查询出来的数据。由于我这里做了MySQL主从复制,因此没有手动往slave添加数据,您可以自行插入几条数据测试。不会MySQL主从复制的请看MySQL主从复制。
INSERT INTO test.t_user_a
(id, name, phone, create_time, update_time)
VALUES(0, '张1', '1724409931630', '2024-08-23 18:45:31', '2024-08-23 18:45:31');