Mybatis-plus框架使用配置

云和惬
2023-12-01

Mybatis-plus框架使用配置

MyBatis-Plus(简称 MP)是一个基于 MyBatis 的增强工具,它对 Mybatis 的基础功能进行了增强,但未做任何改变。使得我们可以可以在 Mybatis 开发的项目上直接进行升级为 Mybatis-plus,正如它对自己的定位,它能够帮助我们进一步简化开发过程,提高开发效率。

Mybatis-Plus 其实可以看作是对 Mybatis 的再一次封装,升级之后,对于单表的 CRUD 操作,调用 Mybatis-Plus 所提供的 API 就能够轻松实现,此外还提供了各种查询方式、分页等行为。最最重要的,开发人员还不用去编写 XML,这就大大降低了开发难度
一、引入依赖

			<dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
                <version>2.3.3.RELEASE</version>
            </dependency>
			<!--mybatis-plus依赖-->
			<dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-annotation</artifactId>
                <version>3.3.2</version>
            </dependency>
			<dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>3.3.2</version>
            </dependency>
            <!--mybatis分页-->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper-spring-boot-starter</artifactId>
                <version>1.2.12</version>
            </dependency>
            <!--mysql依赖-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.9</version>
            </dependency>
            <!--线程池-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>1.1.10</version>
            </dependency>
            <!--工具类-->
           <dependency>
                <groupId>cn.hutool</groupId>
                <artifactId>hutool-all</artifactId>
                <version>5.8.5</version>
            </dependency>
			<dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.21</version>
            </dependency>
            <!--lombok-->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.16</version>
            </dependency>

二、application.yml文件配置

#服务端口号
server:
  port: 9022

#mybatis配置
mybatis-plus:
  mapper-locations: classpath:/mapper/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    call-setters-on-nulls: true

#数据库配置
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/supply_goods?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123456

三、数据库表sql

CREATE TABLE `user` (
  `id` bigint(18) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `username` varchar(255) DEFAULT NULL COMMENT '用户名',
  `password` varchar(255) DEFAULT NULL COMMENT '密码',
  `sex` tinyint(1) DEFAULT NULL COMMENT '性别:0男、1女',
  `dept` varchar(255) DEFAULT NULL COMMENT '部门',
  `created` datetime DEFAULT NULL COMMENT '创建时间',
  `create_by` bigint(20) DEFAULT NULL COMMENT '创建人',
  `modify_by` bigint(20) DEFAULT NULL COMMENT '更新人',
  `last_update_time` datetime DEFAULT NULL COMMENT '更新时间',
  `del_flag` tinyint(1) DEFAULT '0' COMMENT '是否删除:0未删除 1已删除',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

四、实体类
sql在线生成s实体类:https://java.bejson.com/generator/

package com.supplier.domain;

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;

import java.io.Serializable;
import java.util.Date;

/**
 * @description user
 * @author zz
 * @date 2022-11-23
 */
@TableName("user")
@Data
public class User implements Serializable {

    /**
    * id
    */
    @TableId(type = IdType.AUTO)
    private Integer id;

    /**
    * 用户名
    */
    private String username;

    /**
    * 密码
    */
    private String password;

    /**
    * 性别:0男、1女
    */
    private Integer sex;

    /**
    * 部门
    */
    private String dept;

    /**
     * 创建人
     */
    @TableField(value = "create_by", fill = FieldFill.INSERT)
    private String createBy;

    /**
     * 修改人
     */
    @TableField(value = "modify_by", fill = FieldFill.UPDATE)
    private String modifyBy;

    /**
     * 创建时间
     */
    @TableField(value = "created", fill = FieldFill.INSERT)
    private Date created;

    /**
     * 最后更新时间
     */
    @TableField(value = "last_update_time", fill = FieldFill.INSERT_UPDATE)
    private Date lastUpdateTime;

    /**
     * 是否删除1.删除 0.未删除
     */
    private Boolean delFlag;

    /**表示该属性不为数据库表字段,但又是必须使用的。*/
    @TableField(exist = false)
    private String exit;
}

返回实体类

package com.supplier.model;

import com.supplier.constant.SysConstant;
import lombok.Data;

import java.io.Serializable;

/**
 * @author zz
 * @createTime 2021-10-24 18:28
 * @description 公共返回对象值
 */
@Data
public class R<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 状态码
     */
    private int code;

    /**
     * 消息
     */
    private String msg;

    /**
     * 数据
     */
    private T data;

    public static <T> R<T> ok() {
        return restResult(null, SysConstant.SUCCESS_CODE, SysConstant.SUCCESS_MSG);
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, SysConstant.SUCCESS_CODE, SysConstant.SUCCESS_MSG);
    }

    public static <T> R<T> ok(T data, String msg) {
        return restResult(data, SysConstant.SUCCESS_CODE, msg);
    }

    public static <T> R<T> fail() {
        return restResult(null, SysConstant.FAIL_CODE, SysConstant.FAIL_MSG);
    }

    public static <T> R<T> fail(String msg) {
        return restResult(null, SysConstant.FAIL_CODE, msg);
    }

    public static <T> R<T> fail(T data) {
        return restResult(data, SysConstant.FAIL_CODE, SysConstant.FAIL_MSG);
    }

    public static <T> R<T> fail(T data, String msg) {
        return restResult(data, SysConstant.FAIL_CODE, msg);
    }

    public static <T> R<T> fail(int code, String msg) {
        return restResult(null, code, msg);
    }

    private static <T> R<T> restResult(T data, int code, String msg) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }

}
package com.supplier.constant;
/**
 * @author zz
 * @date 2022/10/31 11:26
 */
public interface SysConstant {

    /**
     * 请求成功
     */
    String SUCCESS_MSG = "请求成功!";

    int SUCCESS_CODE = 200;

    /**
     * 请求失败
     */
    String FAIL_MSG = "请求失败!";

    int FAIL_CODE = 500;
}

分页实体类

package com.supplier.model;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.List;

/**
 * @author zz
 * @date 2022-11-02 10:01
 */
@Data
@NoArgsConstructor
public class PageModel<T> implements Serializable {

    /**
     * 页码
     */
    public int pageNum;

    /**
     * 每页显示条数
     */
    public int pageSize;

    /**
     * 总记录
     */
    public long total;

    /**
     * 数据
     */
    public List list;

    /**
     * 全参构造
     */
    public PageModel(int pageNum, int pageSize, long total, List list) {
        this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.total = total;
        this.list = list;
    }

}

五、配置类
mybatis-plus分页配置(也可以直接引入mybatis分页插件)

package com.supplier.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.incrementer.IKeyGenerator;
import com.baomidou.mybatisplus.extension.incrementer.H2KeyGenerator;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author zz
 * @description mybatis-plus
 */
@Configuration
@MapperScan("com.supplier.mapper")
public class MybatisPlusConfig {

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setDbType(DbType.MYSQL);
        return paginationInterceptor;
    }

    /**
     * 乐观锁
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }


    @Bean
    public IKeyGenerator iKeyGenerator() {
        return new H2KeyGenerator();
    }
}

插入、更新时设置字段默认值,更新时必须使用一下方式才生效

package com.supplier.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author zz
 * @createTime 2022-11-02 10:01
 * @description 插入或更新
 */
@Slf4j
@Component
public class AutoFillHandler implements MetaObjectHandler {

    /**
     * 插入
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        String userId = "1234";
        this.strictInsertFill(metaObject, "createBy", String.class, userId);
        this.strictInsertFill(metaObject, "created", Date.class, new Date());
        this.strictInsertFill(metaObject, "lastUpdateTime", Date.class, new Date());
    }

    /**
     * 更新
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        String userId = "22";
        this.strictUpdateFill(metaObject, "modifyBy", String.class, userId);
        this.strictUpdateFill(metaObject, "lastUpdateTime", Date.class, new Date());
    }

}

六、业务逻辑处理(Service接口类)

package com.supplier.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.supplier.domain.User;
import com.supplier.model.PageModel;

/**
 * @author zz
 * @date 2022/11/23 14:34
 */
public interface UserService extends IService<User> {

    /**新增用户
     * @param user 对象
     */
    void add(User user);

    /**更新用户
     * @param user 对象
     */
    void modify(User user);
    
    /**用户详情
     * @param id id
     * @return 结果
     */
    User detail(Integer id);


    /**用户列表
     * @param pageNum 页码
     * @param pageSize 条数
     * @return 结果
     */
    PageModel lists(Integer pageNum,Integer pageSize);

    /**删除用户
     * @param id id
     */
    void delete(Integer id);
}

实现类

package com.supplier.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.supplier.domain.User;
import com.supplier.mapper.UserMapper;
import com.supplier.model.PageModel;
import com.supplier.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zz
 * @date 2022/11/23 14:34
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Override
    public void add(User user) {
        this.baseMapper.insert(user);
    }

    @Override
    public void modify(User user) {
        //当重新new对象时,会调用自动填充更新时间和更新人的数据
        User userNews = new User();
        BeanUtil.copyProperties(user,userNews);
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.eq("id",user.getId());
        this.baseMapper.update(user,userUpdateWrapper);
    }

    @Override
    public User detail(Integer id) {
        //需要筛选条件时
        return this.baseMapper.selectOne(new QueryWrapper<User>().eq("id",id).last("limit 1"));
    }


    public PageModel listsTwo(Integer pageNum,Integer pageSize) {
        //第一种分页,使用mybatis插件
        PageHelper.startPage(pageNum,pageSize);
        Page<User> list = this.baseMapper.lists();
        return new PageModel(pageNum,pageSize,list.getTotal(),list.getResult());
    }

    @Override
    public PageModel lists(Integer pageNum,Integer pageSize){
        //第二种分页,mybatis-plus分页
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<User> userPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum,pageSize);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<User> list = this.baseMapper.selectPage(userPage, null);
        return new PageModel(pageNum,pageSize,list.getTotal(),list.getRecords());
    }

    public List<User> selectInfo(String username, Integer sex) {
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        //使用eq表示查询值为必填,select表示查询字段
        queryWrapper.like(StringUtils.isNoneBlank(username),"username",username).eq("sex",sex).select("id","username");
        //无查询条件
        return this.baseMapper.selectList(queryWrapper);
    }


    @Override
    public void delete(Integer id) {
        this.baseMapper.deleteById(id);
    }
}

七、数据访问层(dao接口类)

package com.supplier.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.github.pagehelper.Page;
import com.supplier.domain.User;
import org.apache.ibatis.annotations.Mapper;
/**
 * @author zz
 * @date 2022/11/23 14:35
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {

    Page<User> lists();
}

mapper文件

<?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.supplier.mapper.UserMapper">

    <select id="lists" resultType="com.supplier.domain.User">
        select * from `user`
    </select>
</mapper>

八、控制层(controller)

package com.supplier.controller;

import com.supplier.domain.User;
import com.supplier.model.R;
import com.supplier.service.UserService;
import org.springframework.web.bind.annotation.*;

/**
 * @author zz
 * @date 2022/11/23 14:34
 */
@RestController
@RequestMapping("/user")
public class UserController {


    private final UserService userService;


    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 新增用户
     */
    @PostMapping
    public R add(@RequestBody User user){
        userService.add(user);
        return R.ok();
    }

    /**
     * 更新用户
     */
    @PutMapping
    public R modify(@RequestBody User user){
        userService.modify(user);
        return R.ok();
    }

    /**
     * 用户详情
     */
    @GetMapping("/{id}")
    public R detail(@PathVariable Integer id){
        return R.ok(userService.detail(id));
    }

    /**
     * 用户列表
     */
    @GetMapping
    public R list(@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "10")Integer pageSize){
        return R.ok(userService.lists(pageNum,pageSize));
    }


    /**
     * 更新用户
     */
    @DeleteMapping
    public R delete(Integer id){
        userService.delete(id);
        return R.ok();
    }

}

 类似资料: