springBoot集成mybatis-plus

springBoot集成mybatis-plus

  • 1.环境搭建
  • 2.造数据代码
  • 3.CRUD 接口
    • 1.如何配置统一的逻辑删除
    • 2.pojo层的CRUD 接口
    • 3.mapper层的CRUD 接口
    • 4.service层的CRUD 接口
  • 4.新增或删除如何用
    • 1.pojo层的方法为:insertOrUpdate()
    • 2.mapper层没有
    • 3.service层的方法为:saveOrUpdate()
  • 5.分页查询
    • 1.在代码中的用法
    • 2.xml文件中的使用

1.环境搭建

1.sql

CREATE TABLE `t_user` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id',
  `name` varchar(32) COLLATE utf8mb4_general_ci NOT NULL COMMENT '姓名',
  `age` int NOT NULL COMMENT '年龄',
  `password` varchar(20) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '密码',
  `sex` char(8) COLLATE utf8mb4_general_ci NOT NULL,
  `create_time` timestamp(6) NULL DEFAULT NULL,
  `is_del` tinyint(1) DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `t_user_pk2` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='用户表';

2.创建maven工程并且导入坐标


<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.0modelVersion>

    <groupId>com.andygroupId>
    <artifactId>springboot_crudartifactId>
    <version>1.0-SNAPSHOTversion>

    <properties>
        <maven.compiler.source>11maven.compiler.source>
        <maven.compiler.target>11maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>
    <parent>
        <artifactId>spring-boot-starter-parentartifactId>
        <groupId>org.springframework.bootgroupId>
        <version>2.7.13version>
    parent>
    <dependencies>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13.2version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-restartifactId>
        dependency>
        <dependency>
            <groupId>com.alibaba.fastjson2groupId>
            <artifactId>fastjson2artifactId>
            <version>2.0.40version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.33version>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.26version>
            <scope>providedscope>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.5.3.1version>
        dependency>
    dependencies>
project>

3.application.yml文件中的配置

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/study_test
    username: root
    password: root
mybatis-plus:
  # 包扫描
  type-aliases-package: com.andy.pojo
  # 加载Mapper.xml文件
  mapper-locations: classpath:/mapper/*.xml
  configuration:
    # 输出日志
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

4.pojo层

package com.andy.pojo;

import com.alibaba.fastjson2.annotation.JSONField;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.sql.Timestamp;


@Data
@EqualsAndHashCode(callSuper = true)
@TableName(value = "t_user")
public class User extends Model<User> {

    private static final long serialVersionUID = 3404898457642193846L;
    /**
     * ID
     */
    @TableId(value = "id",type = IdType.AUTO)
    @JSONField(ordinal = 0)
    private Long id;
    /**
     * 姓名
     */
    @JSONField(ordinal = 1)
    private String name;
    /**
     * 密码
     */
    @JSONField(ordinal = 2)
    private String password;
    /**
     * 年龄
     */
    @JSONField(ordinal = 3)
    private Integer age;
    /**
     * 性别
     */
    @JSONField(ordinal = 4)
    private String  sex;
    /**
     * 时间
     */
    @JSONField(ordinal = 5)
    private Timestamp createTime;
    /**
     * 逻辑删除
     */
    @TableLogic
    @JsonIgnore
    private Boolean isDel;
}

4.mapper层

package com.andy.mapper;

import com.andy.pojo.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

/**
 * @author andy
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {

}

5.service层

package com.andy.service;

import com.andy.pojo.User;
import com.baomidou.mybatisplus.extension.service.IService;


public interface IUserService extends IService<User> {

}

6.serviceImpl层

package com.andy.service.impl;

import com.andy.mapper.UserMapper;
import com.andy.pojo.User;
import com.andy.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

}

7.测试类代码

package com.andy.mybatis.user;

import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @author Andy
 * @version 0.0.1
 * @since 2023-10-11 14:22
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestService {

}

2.造数据代码

1.在service层定义
springBoot集成mybatis-plus_第1张图片

    /**
     * 测试数据
     * @param startId 开始id
     * @param endId 结束ID
     * @throws InterruptedException /
     */
    void saveTest(Integer startId, Integer endId) throws InterruptedException;
   

2.实现saveTest接口

@Override
@Transactional(rollbackFor = Exception.class)
public void saveTest(Integer startId, Integer endId) throws InterruptedException {
    ThreadLocalRandom current = ThreadLocalRandom.current();
    List<User> users = new ArrayList<>(endId + 1);
    for (int i = startId; i < endId + 1; i++) {
        User userTest = new User();
        userTest.setId((long) i);
        userTest.setName(getName());
        userTest.setPassword(String.valueOf(current.nextInt(100000,1000000)));
        userTest.setSex(String.valueOf(current.nextInt(0, 2)).equals("1") ?"男":"女");
        userTest.setAge(current.nextInt(10, 50));
        userTest.setCreateTime(new Timestamp(ThreadLocalRandom.current().nextLong(1307008513279L,1697008513279L)));
        userTest.setIsDel(Boolean.FALSE);
        users.add(userTest);
    }
    Integer index = startId;
    List<User> sortedUsers = users.stream().sorted(Comparator.comparing(User::getCreateTime)).collect(Collectors.toList());
    for (User sortedUser : sortedUsers) {
        sortedUser.setId((long) startId);
        startId++;
    }
    this.saveBatch(sortedUsers);
}

// 姓氏池
private static final String SURNAME = "赵钱孙李周吴郑王冯陈卫蒋沈韩杨朱许";
// 名字池
private static final String NAME = "三四五六七八安星楠希拧允言遥初乐依宇苏思诺";

public static String getName() {
    // 开局获取一个姓氏池的随机下标
    int surnameLength = (int) (Math.random() * (SURNAME.length()));
    // 通过下标随机获取到一个姓氏
    char c = SURNAME.charAt(surnameLength);
    // 创建一个可扩容字符串
    StringBuilder userName = new StringBuilder();
    // 将随机获取到的姓氏拼接
    userName.append(c);
    // 随机(1,3]的随机数(一般名字要么是两个字要么一个字)
    int nameLength = (int) (Math.random() * 3);
    // 判断随机数是否大于1 如果大于 1那么就进行两次随机获取名字池的某个字符,进行拼接
    if (nameLength > 1) {
        // int i1 = (int) (Math.random() * (NAME.length()));
        int i1 = ThreadLocalRandom.current().nextInt(NAME.length());
        char c1 = NAME.charAt(i1);
        // int i2 = (int) (Math.random() * (NAME.length()));
        int i2 = ThreadLocalRandom.current().nextInt(NAME.length());
        char c2 = NAME.charAt(i2);
        userName.append(c1);
        userName.append(c2);
        return String.valueOf(userName);
        // 其他情况下就是一个字的名字,只获取一个字
    } else {
        int i1 = (int) (Math.random() * (NAME.length()));
        char c1 = NAME.charAt(i1);
        userName.append(c1);
        return String.valueOf(userName);
    }
}

3.在测试类TestService编写代码:

@Resource
private IUserService userService;

/**
 * 生成测试数据
 */
@Test
public void testDataSave() throws InterruptedException {
    userService.saveTest(1,5);
}

4.运行结果

springBoot集成mybatis-plus_第2张图片
5.数据库验证查询

select * from t_user;

springBoot集成mybatis-plus_第3张图片

3.CRUD 接口

1.如何配置统一的逻辑删除

1.案例如下:

删除: update user set is_del=1 where id = 1 and is_del=0
查找: select id,name,is_del from user where is_del=0

2.在yml文件中配置如下内容:

mybatis-plus:
  global-config:
    db-config:
      # 全局逻辑删除字段
      logic-delete-field: is_del 
      # 逻辑已删除值(默认为 1)
      logic-delete-value: 1 
      # 逻辑未删除值(默认为 0)
      logic-not-delete-value: 0 

2.pojo层的CRUD 接口

1.新增

@Test
public void testPojoSave(){
    User user = new User();
    user.setName("root");
    user.setPassword("123456");
    user.setAge(30);
    user.setCreateTime(new Timestamp(System.currentTimeMillis()));
    user.setSex("男");
    // 新增
    user.insert();
}

2.查询

@Test
public void testPojoRead(){
    User user = new User();
    // 查询所有
    System.out.println(user.selectAll());
    // 更具ID查询
    System.out.println(user.selectById(1));
}

3.更新

@Test
public void testPojoUpdate(){
    User user = new User();
    // id必须有
    user.setId(1L);
    user.setName("aaa");
    user.updateById();
}

4.删除(逻辑删除)

@Test
public void testPojoDelete(){
   User user = new User();
   user.setId(1L);
   user.deleteById();
}

数据库验证SQL:

select * from t_user

springBoot集成mybatis-plus_第4张图片
5.本节完整代码

package com.andy.mybatis.user;

import com.andy.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.sql.Timestamp;

/**
 * @author Andy
 * @version 0.0.1
 * @since 2023-10-12 11:12
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestPojo {
    /**
     * 新增
     */
    @Test
    public void testPojoSave(){
        User user = new User();
        user.setName("root");
        user.setPassword("123456");
        user.setAge(30);
        user.setCreateTime(new Timestamp(System.currentTimeMillis()));
        user.setSex("男");
        // 新增
        user.insert();

    }
    /**
     * 查询
     */
    @Test
    public void testPojoRead(){
        User user = new User();
        // 查询所有
        System.out.println(user.selectAll());
        // 更具ID查询
        System.out.println(user.selectById(1));
    }
    /**
     * 修改
     */
    @Test
    public void testPojoUpdate(){

        User user = new User();
        // id必须有
        user.setId(1L);
        user.setName("aaa");
        user.updateById();
    }
    /**
     * 逻辑删除
     */
    @Test
    public void testPojoDelete(){
        User user = new User();
        user.setId(1L);
        user.deleteById();
    }
}


3.mapper层的CRUD 接口

注意:使用Mapper层时要将Mapper进行注入:代码如下

 @Resource
 private UserMapper userMapper;

1.新增

@Test
public void testMapperSave(){

    User user = new User();
    user.setName("bbb");
    user.setPassword("123456");
    user.setAge(30);
    user.setCreateTime(new Timestamp(System.currentTimeMillis()));
    user.setSex("女");
    userMapper.insert(user);
}

数据库验证SQL

select * from t_user

springBoot集成mybatis-plus_第5张图片

2.查询

@Test
public void testMapperRead(){
    System.out.println(userMapper.selectById(1L));
    System.out.println(userMapper.selectList(null));
}

3.更新

@Test
public void testMapperUpdate(){
    User user = new User();
    user.setId(7L);
    user.setSex("男");
    userMapper.updateById(user);
}

4.删除

public void testMapperDelete(){
    userMapper.deleteById(2L);
}

数据库验证SQL

select * from t_user

springBoot集成mybatis-plus_第6张图片

5.本节完整代码

package com.andy.mybatis.user;

import com.andy.mapper.UserMapper;
import com.andy.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.sql.Timestamp;

/**
 * @author Andy
 * @version 0.0.1
 * @since 2023-10-12 14:23
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestMapper {

    @Resource
    private UserMapper userMapper;
    /**
     * 新增
     */
    @Test
    public void testMapperSave(){

        User user = new User();
        user.setName("bbb");
        user.setPassword("123456");
        user.setAge(30);
        user.setCreateTime(new Timestamp(System.currentTimeMillis()));
        user.setSex("女");
        userMapper.insert(user);
    }
    /**
     * 查询
     */
    @Test
    public void testMapperRead(){
    	// 根据ID查询
        System.out.println(userMapper.selectById(1L));
        // 查询所有
        System.out.println(userMapper.selectList(null));
    }
    /**
     * 更新
     */
    @Test
    public void testMapperUpdate(){
        User user = new User();
        user.setId(7L);
        user.setSex("男");
        userMapper.updateById(user);
    }
    /**
     * 逻辑删除
     */
    @Test
    public void testMapperDelete(){
        userMapper.deleteById(2L);
    }
}

4.service层的CRUD 接口

注意:使用Mapper层时要将Mapper进行注入:代码如下

 @Resource
 private IUserService userService;

1.新增

@Test
public void testServiceSave() {
    User user = new User();
    user.setName("root");
    user.setPassword("123456");
    user.setAge(30);
    user.setCreateTime(new Timestamp(System.currentTimeMillis()));
    user.setSex("男");
    userService.save(user);
}

2.查询

@Test
public void testServiceRead() {
    // 查询所有
    System.out.println(userService.list());
    // 根据ID查询
    System.out.println(userService.getById(1L));
}

3.更新

@Test
public void testServiceUpdate() {
    User user = new User();
    user.setId(8L);
    user.setName("ccc");
    user.setCreateTime(new Timestamp(System.currentTimeMillis()));
    userService.updateById(user);
}

4.删除

@Test
public void testServiceDelete() {
    userService.removeById(3L);
}

5.本节完整代码

package com.andy.mybatis.user;

import com.andy.pojo.User;
import com.andy.service.IUserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.sql.Timestamp;

/**
 * @author Andy
 * @version 0.0.1
 * @since 2023-10-12 14:22
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestService {

    @Resource
    private IUserService userService;

    /**
     * 新增
     */
    @Test
    public void testServiceSave() {
        User user = new User();
        user.setName("root");
        user.setPassword("123456");
        user.setAge(30);
        user.setCreateTime(new Timestamp(System.currentTimeMillis()));
        user.setSex("男");
        userService.save(user);
    }
    /**
     * 查询
     */
    @Test
    public void testServiceRead() {
        // 查询所有
        System.out.println(userService.list());
        // 根据ID查询
        System.out.println(userService.getById(1L));
    }
    /**
     * 修改
     */
    @Test
    public void testServiceUpdate() {
        User user = new User();
        user.setId(8L);
        user.setName("ccc");
        user.setCreateTime(new Timestamp(System.currentTimeMillis()));
        userService.updateById(user);
    }
    /**
     * 删除
     */
    @Test
    public void testServiceDelete() {
        userService.removeById(3L);
    }
}

4.新增或删除如何用

1.pojo层的方法为:insertOrUpdate()

1.无d的情况:

    @Test
    public void testPojoInsertOrUpdate(){
        User user = new User();
        user.setName("ddd");
        user.setPassword("123456");
        user.setAge(30);
        user.setCreateTime(new Timestamp(System.currentTimeMillis()));
        user.setSex("男");
        user.insertOrUpdate();
    }

2.测试结果
springBoot集成mybatis-plus_第7张图片
3.结论:没有ID就会新增

4.有ID的情况:

@Test
public void testPojoInsertOrUpdate(){
    User user = new User();
    user.setId(9L);
    user.setName("xxx");
    user.setPassword("123456");
    user.setAge(30);
    user.setCreateTime(new Timestamp(System.currentTimeMillis()));
    user.setSex("男");
    user.insertOrUpdate();
}

springBoot集成mybatis-plus_第8张图片
5.结论:有ID就会更新

2.mapper层没有

3.service层的方法为:saveOrUpdate()

1.无d的情况:

@Test
public void testPojoInsertOrUpdate(){
    User user = new User();
    user.setName("eee");
    user.setPassword("123456");
    user.setAge(30);
    user.setCreateTime(new Timestamp(System.currentTimeMillis()));
    user.setSex("男");
    userService.saveOrUpdate(user);
}

2.有id的情况;

@Test
public void testPojoInsertOrUpdate(){
    User user = new User();
    user.setId(10L);
    user.setName("gggg");
    user.setPassword("123456");
    user.setAge(30);
    user.setCreateTime(new Timestamp(System.currentTimeMillis()));
    user.setSex("男");
    userService.saveOrUpdate(user);
}

3.结论:有id就会更新,没有id就会新增

5.分页查询

1.配置类

@Configuration
@MapperScan("scan.your.mapper.package")
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
    
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //如果配置多个插件,切记分页最后添加
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        
        //interceptor.addInnerInterceptor(new PaginationInnerInterceptor()); 如果有多数据源可以不配具体类型 否则都建议配上具体的DbType
        
        return interceptor;
    }
}

2.查询当前表数据
springBoot集成mybatis-plus_第9张图片

1.在代码中的用法

1.service层代码

@Test
public void testServicePage(){
	// 第1页 每页3条数据
    IPage<User> userIPage = new Page<>(1,3);
    IPage<User> pageData = userService.page(userIPage);
    // 结果数据
    System.out.println(pageData.getRecords());
    // 当前页
    System.out.println(pageData.getCurrent());
    // 当前页总数
    System.out.println(pageData.getSize());
    // 总数
    System.out.println(pageData.getTotal());
}

2.mapper层代码

@Test
public void testMapperPage(){
	// 第1页 每页3条数据
    IPage<User> userIPage = new Page<>(1,3);
    IPage<User> pageData = userMapper.selectPage(userIPage,null);
    // 结果数据
    System.out.println(pageData.getRecords());
    // 当前页
    System.out.println(pageData.getCurrent());
    // 当前页总数
    System.out.println(pageData.getSize());
    // 总数
    System.out.println(pageData.getTotal());
}

3.pojo层代码

@Test
public void testPojoPage(){
	// 第1页 每页3条数据
    IPage<User> userIPage = new Page<>(1,3);
    User user = new User();
    IPage<User> pageData = user.selectPage(userIPage,null);
    // 结果数据
    System.out.println(pageData.getRecords());
    // 当前页
    System.out.println(pageData.getCurrent());
    // 当前页总数
    System.out.println(pageData.getSize());
    // 总数
    System.out.println(pageData.getTotal());
}

2.xml文件中的使用

1.在UserMapper中定义接口

IPage<User> findByPage(IPage<User> page);

2.xml文件配置

    <select id="findByPage" resultType="com.andy.pojo.User">
        select * from t_user where is_del = 0
    select>

3.测试代码

    @Test
    public void testMapperPage(){
        IPage<User> userIPage = new Page<>(1,3);

        // 第1页 每页3条数据
        IPage<User> pageData = userMapper.findByPage(userIPage);

        // 结果数据
        System.out.println(pageData.getRecords());
        // 当前页
        System.out.println(pageData.getCurrent());
        // 当前页总数
        System.out.println(pageData.getSize());
        // 总数
        System.out.println(pageData.getTotal());
    }

你可能感兴趣的:(spring,boot,mybatis,后端)