【Spring Boot】如何集成mybatis-plus

  1. 在pom文件中导入maven坐标
    1.

    XML 复制代码
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.23</version>
            </dependency>
            <!--mybatis-plus-->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>3.4.2</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.23</version>
            </dependency>
  2. 创建maven项目的目录结构

  3. 创建ResultBean作为返回包装类
    1.

    java 复制代码
    package com.app.user.common;
    
    import lombok.Data;
    
    import java.io.Serializable;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * 返回bean信息
     *
     * @author Administrator
     */
    @Data
    public class ResultBean<T> implements Serializable {
    
        private static final long serialVersionUID = -6759928086797729382L;
        /**
         * 编码:1成功,0和其它数字为失败
         */
        private Integer code;
        /**
         * 错误信息
         */
        private String msg;
        /**
         * 数据
         */
        private T data;
        /**
         * 动态数据
         */
        private Map map = new HashMap();
    
        public static <T> ResultBean<T> success(T object) {
            ResultBean<T> r = new ResultBean<T>();
            r.data = object;
            r.code = 1;
            return r;
        }
    
        public static <T> ResultBean<T> error(String msg) {
            ResultBean r = new ResultBean();
            r.msg = msg;
            r.code = 0;
            return r;
        }
    
        public ResultBean<T> add(String key, Object value) {
            this.map.put(key, value);
            return this;
        }
    
    }
  4. 创建mybatis plus的分页配置信息
    1.

    java 复制代码
    package com.app.user.config;
    
    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;
    
    /**
     * 配置MybatisPlus的配置信息
     *
     * @author Administrator
     */
    @Configuration
    public class MybatisPlusConfig {
    
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() {
            // 获取MybatisPlus的拦截器链
            MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
            // 添加分页拦截器PaginationInnerInterceptor,实现自动分页
            mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
            return mybatisPlusInterceptor;
        }
    
    }
  5. 创建表实体类信息
    1.

    java 复制代码
    package com.app.user.pojo;
    
    import com.baomidou.mybatisplus.annotation.TableName;
    import lombok.Data;
    
    /**
     * 用户实体类
     *
     * @author Administrator
     */
    @Data
    @TableName(value = "tb_user")
    public class User {
        /**
         * 主键
         */
        private Long id;
        /**
         * 用户名
         */
        private String username;
        /**
         * 联系电话
         */
        private String phone;
    
    }
  6. 创建mapper类
    1.

    java 复制代码
    package com.app.user.mapper;
    
    
    import com.app.user.pojo.User;
    import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    import org.apache.ibatis.annotations.Mapper;
    
    /**
     * 用户mapper
     *
     * @author Administrator
     */
    @Mapper
    public interface UserMapper extends BaseMapper<User> {
        /**
         * 计算数目
         *
         * @return 返回计算数目
         */
        int countNum();
    
    }
  7. 创建服务接口类
    1.

    java 复制代码
    package com.app.user.service;
    
    
    import com.app.user.pojo.User;
    import com.baomidou.mybatisplus.extension.service.IService;
    
    /**
     * 用户服务接口
     *
     * @author Administrator
     */
    public interface UserService extends IService<User> {
    
        /**
         * 计算数目
         *
         * @return 返回记录数
         */
        int countNum();
    
    }
  8. 创建服务接口类实现类
    1.

    java 复制代码
    package com.app.user.service.impl;
    
    
    import com.app.user.mapper.UserMapper;
    import com.app.user.pojo.User;
    import com.app.user.service.UserService;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import org.springframework.stereotype.Service;
    
    /**
     * 用户服务
     *
     * @author Administrator
     */
    @Service
    public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    
        @Override
        public int countNum() {
            // 使用原生的xml文件mapper查询表记录
            return this.baseMapper.countNum();
        }
    
    }
  9. 创建服务的controller类
    1.

    java 复制代码
    package com.app.user.controller;
    
    
    import cn.hutool.core.util.StrUtil;
    import com.app.user.common.ResultBean;
    import com.app.user.pojo.User;
    import com.app.user.service.UserService;
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
    import lombok.RequiredArgsConstructor;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.web.bind.annotation.*;
    
    import javax.servlet.http.HttpServletRequest;
    
    /**
     * 用户控制器
     *
     * @author Administrator
     */
    @RestController
    @RequestMapping("/users")
    @Slf4j
    @RequiredArgsConstructor
    public class UserController {
    
        /**
         * 结合@RequiredArgsConstructor进行构造器注入
         */
        private final UserService userService;
    
        /**
         * 新增用户
         *
         * @param user 用户信息
         * @return 用户信息
         */
        @PostMapping
        public ResultBean<User> save(@RequestBody User user) {
            log.info("新增用户,用户信息:{}", user.toString());
            userService.save(user);
            return ResultBean.success(user);
        }
    
        /**
         * 根据id修改用户信息
         *
         * @param user 用户信息
         * @return 修改提示信息
         */
        @PutMapping
        public ResultBean<String> update(HttpServletRequest request, @RequestBody User user) {
            log.info(user.toString());
            userService.updateById(user);
            return ResultBean.success("用户信息修改成功");
        }
    
        /**
         * 根据id查询用户信息
         *
         * @param id 用户id
         * @return 用户信息
         */
        @GetMapping("/{id}")
        public ResultBean<User> getById(@PathVariable Long id) {
            log.info("根据id查询用户信息...");
            User user = userService.getById(id);
            if (user != null) {
                return ResultBean.success(user);
            }
            return ResultBean.error("没有查询到对应用户信息");
        }
    
        /**
         * 用户信息分页
         *
         * @param page     当前页
         * @param pageSize 每页显示条数
         * @param username 用户名
         * @return 返回分页用户信息
         */
        @GetMapping("/page")
        public ResultBean<Page<User>> page(int page, int pageSize, String username) {
            log.info("page = {},pageSize = {},username = {}", page, pageSize, username);
            // 1、构造简单分页模型
            Page<User> pageInfo = new Page<>(page, pageSize);
            // 2、构造条件构造器
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            // 3、添加用户名过滤条件,使用模糊匹配,不为空时才生效
            queryWrapper.like(StrUtil.isNotEmpty(username), User::getUsername, username);
            // 4、添加排序条件
            queryWrapper.orderByDesc(User::getId);
            // 5、执行查询,查询的结果将会直接存在于pageInfo对象中
            userService.page(pageInfo, queryWrapper);
            return ResultBean.success(pageInfo);
        }
    
        /**
         * 获取用户记录数
         *
         * @return 返回记录数
         */
        @GetMapping("/count")
        public ResultBean<Integer> count() {
            log.info("计算用户数目...");
            int i = userService.countNum();
            return ResultBean.success(i);
        }
    
    }
  10. 在resources的文件夹创建mapper文件夹,并创建mapper.xml文件,示例创建的是UserMapper.xml文件
    1.

    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="com.app.user.mapper.UserMapper">
    
        <resultMap id="BaseResultMap" type="com.app.user.pojo.User">
            <result property="id" column="id" jdbcType="DECIMAL"/>
            <result property="username" column="username" jdbcType="VARCHAR"/>
            <result property="phone" column="phone" jdbcType="VARCHAR"/>
        </resultMap>
    
        <sql id="Base_Column_List">
            id,username,phone
        </sql>
    
        <select id="countNum" resultType="int">
            select count(*)
            from tb_user;
        </select>
    
    </mapper>
  11. 创建application.yml文件并配置下列信息
    1.

    XML 复制代码
    server:
      port: 8080
    spring:
      application:
        #应用的名称,可选
        name: user-service
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3333/user_demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
        username: root
        password: 123456
        type: com.alibaba.druid.pool.DruidDataSource
    
    mybatis-plus:
      configuration:
        #在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射
        map-underscore-to-camel-case: true
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
      global-config:
        db-config:
          id-type: ASSIGN_ID
      mapper-locations: classpath:mapper/*.xml
  12. 创建logback.xml日志文件并配置下列信息
    1.

    XML 复制代码
    <?xml version="1.0" encoding="UTF-8"?>
    <!--
      ~ Licensed to the Apache Software Foundation (ASF) under one or more
      ~ contributor license agreements.  See the NOTICE file distributed with
      ~ this work for additional information regarding copyright ownership.
      ~ The ASF licenses this file to You under the Apache License, Version 2.0
      ~ (the "License"); you may not use this file except in compliance with
      ~ the License.  You may obtain a copy of the License at
      ~
      ~     http://www.apache.org/licenses/LICENSE-2.0
      ~
      ~ Unless required by applicable law or agreed to in writing, software
      ~ distributed under the License is distributed on an "AS IS" BASIS,
      ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      ~ See the License for the specific language governing permissions and
      ~ limitations under the License.
      -->
    
    <configuration>
        <property name="log.context.name" value="sharding-jdbc-spring-namespace-mybatis-example" />
        <property name="log.charset" value="UTF-8" />
        <property name="log.pattern" value="[%-5level] %date --%thread-- [%logger] %msg %n" />
        <contextName>${log.context.name}</contextName>
    
        <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
            <encoder charset="${log.charset}">
                <pattern>${log.pattern}</pattern>
            </encoder>
        </appender>
        <root>
            <level value="info" />
            <appender-ref ref="STDOUT" />
        </root>
    </configuration>
  13. 直接启动SpringBootApplication启动类即可

相关推荐
KATA~1 分钟前
解决MyBatis-Plus枚举映射错误:No enum constant问题
java·数据库·mybatis
xyliiiiiL17 分钟前
一文总结常见项目排查
java·服务器·数据库
shaoing19 分钟前
MySQL 错误 报错:Table ‘performance_schema.session_variables’ Doesn’t Exist
java·开发语言·数据库
腥臭腐朽的日子熠熠生辉1 小时前
解决maven失效问题(现象:maven中只有jdk的工具包,没有springboot的包)
java·spring boot·maven
ejinxian1 小时前
Spring AI Alibaba 快速开发生成式 Java AI 应用
java·人工智能·spring
杉之1 小时前
SpringBlade 数据库字段的自动填充
java·笔记·学习·spring·tomcat
圈圈编码2 小时前
Spring Task 定时任务
java·前端·spring
俏布斯2 小时前
算法日常记录
java·算法·leetcode
27669582922 小时前
美团民宿 mtgsig 小程序 mtgsig1.2 分析
java·python·小程序·美团·mtgsig·mtgsig1.2·美团民宿
爱的叹息2 小时前
Java 连接 Redis 的驱动(Jedis、Lettuce、Redisson、Spring Data Redis)分类及对比
java·redis·spring