SpringBoot 2.7.18 集成 Mybatis Plus + Druid

目录

一并附上 Mybatis 和 Mybatis Plus 的使用区别

Pom 依赖

Mybatis

xml 复制代码
<!-- 统一管理 jar 包版本 -->
<properties>
    <druid-boot.version>1.1.10</druid-boot.version>
    <mybatis-boot.version>2.1.0</mybatis-boot.version>
    <mysql-connector.version>8.0.16</mysql-connector.version>
    <mssql-jdbc.version>8.2.2.jre8</mssql-jdbc.version>
    <oracle-jdbc.version>19.3.0.0</oracle-jdbc.version>
    <pagehelper-starter.version>1.2.10</pagehelper-starter.version>
</properties>

<!--子模块继承之后,锁定版本+子模块不用写 groupid 和 version -->
<dependencyManagement>
    <dependencies>
        <!-- mybatis + druid + mysql + mssql-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${druid-boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis-boot.version}</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>${pagehelper-starter.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector.version}</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>${mssql-jdbc.version}</version>
        </dependency>
        <dependency>
            <groupId>com.oracle.database.jdbc</groupId>
            <artifactId>ojdbc8</artifactId>
            <version>${oracle-jdbc.version}</version>
        </dependency>
        <!-- mybatis + druid + mysql + mssql-->
    </dependencies>
</dependencyManagement>

Mybatis Plus

使用框架自带的分布控件,如果使用 pagehelper 会报 JSqlParser 的版本冲突,根据情况排除 pagehelper 版本(不推荐)。

xml 复制代码
<!-- 统一管理 jar 包版本 -->
<properties>
    <druid-boot.version>1.2.23</druid-boot.version>
    <mybatis-plus.version>3.5.7</mybatis-plus.version>
    <mysql-connector.version>8.0.33</mysql-connector.version>
    <mssql-jdbc.version>8.2.2.jre8</mssql-jdbc.version>
    <oracle-jdbc.version>19.3.0.0</oracle-jdbc.version>
</properties>

<!--子模块继承之后,锁定版本+子模块不用写 groupid 和 version -->
<dependencyManagement>
    <dependencies>
        <!-- mybatis plus + druid + mysql + mssql-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-extension</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-annotation</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${druid-boot.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>${mysql-connector.version}</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>${mssql-jdbc.version}</version>
        </dependency>
        <dependency>
            <groupId>com.oracle.database.jdbc</groupId>
            <artifactId>ojdbc8</artifactId>
            <version>${oracle-jdbc.version}</version>
        </dependency>
        <!-- mybatis plus + druid + mysql + mssql-->
    </dependencies>
</dependencyManagement>

yml 配置

Mybatis

yml 复制代码
mybatis:
  # 指定sql映射文件位置
  mapper-locations: classpath*:mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  type-handlers-package: com.vipsoft.base.handler # MySQL 8.0  用以mysql中json格式的字段,进行转换的自定义转换器,转换为实体类的JSONObject属性

Mybatis-Plus

yml 复制代码
mybatis-plus:
  mapper-locations: classpath*:mapper/*Mapper.xml
  global-config:
    banner: true
    db-config:
      id-type: auto
      where-strategy: not_empty
      insert-strategy: not_empty
      update-strategy: not_null
  type-handlers-package: com.vipsoft.base.handler # MySQL 8.0  用以mysql中json格式的字段,进行转换的自定义转换器,转换为实体类的JSONObject属性
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    map-underscore-to-camel-case: true
    jdbc-type-for-null: 'null'
    call-setters-on-nulls: true
    shrink-whitespaces-in-sql: true

Config 配置

Mybatis Plus 分页,需要添加 拦截器配置,否则分页不生效

java 复制代码
package com.vipsoft.base.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;

@Configuration
public class MybatisPlusConfig {

    /**
     * 分页插件 -- 否则分页不生效
     * @return
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }
}

Mapper扫描

@MapperScan({"com.vipsoft.admin.mapper"}) 和 Mybatis 无区别

java 复制代码
package com.vipsoft.admin;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; 
import org.springframework.context.annotation.ComponentScan;


@ComponentScan(basePackages = {"com.vipsoft"})
@SpringBootApplication
@MapperScan({"com.vipsoft.admin.mapper"})
public class VipSoftAdminApplication {

    public static void main(String[] args) {
        SpringApplication.run(VipSoftAdminApplication.class, args);
    }
}

Entity

SysMenu

java 复制代码
//@TableName("sys_menu") 默认会将 SysMenu 解析成 sys_menu 如果解析后不是正确的表名,需要通过 TableName进行指定,
public class SysMenu extends BaseEntity
{
    private static final long serialVersionUID = 1L;

    /** 菜单ID */
	@TableId(value = "menu_id", type = IdType.ASSIGN_ID)
    private Long menuId;

    /** 菜单名称 */
	@TableField(value = "menu_name")
    private String menuName;

    /** 父菜单名称 */
    @TableField(exist = false)  //非数据库字段,进行排除
    private String parentName;
	....省略
}

Mapper.xml

SysMenuMapper.xml

java 复制代码
<?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.vipsoft.admin.mapper.SysMenuMapper">

    <resultMap type="com.vipsoft.admin.entity.SysMenu" id="SysMenuResult">
        <id property="menuId" column="menu_id"/>
        <result property="menuName" column="menu_name"/>
        <result property="parentName" column="parent_name"/>
        <result property="parentId" column="parent_id"/>
        <result property="orderNum" column="order_num"/>
        <result property="path" column="path"/> 
        <result property="createTime" column="create_time"/>
        <result property="updateTime" column="update_time"/> 
    </resultMap>

    <select id="listMenu" parameterType="com.vipsoft.admin.entity.SysMenu" resultMap="SysMenuResult">
        select menu_id, menu_name, parent_id, order_num, create_time from sys_menu
        <where>
            <if test="menuName != null and menuName != ''">
                AND menu_name like concat('%', #{menuName}, '%')
            </if>
            <if test="visible != null and visible != ''">
                AND visible = #{visible}
            </if>
            <if test="status != null and status != ''">
                AND status = #{status}
            </if>
        </where>
        order by parent_id, order_num
    </select>

    <select id="listMenuPage" resultMap="SysMenuResult">
        select menu_id, menu_name, parent_id, order_num, create_time from sys_menu
        <where>
            <if test="query.menuName != null and query.menuName != ''">
                AND menu_name like concat('%', #{query.menuName}, '%')
            </if>
            <if test="query.visible != null and query.visible != ''">
                AND visible = #{query.visible}
            </if>
            <if test="query.status != null and query.status != ''">
                AND status = #{query.status}
            </if>
        </where>
        order by parent_id, order_num
    </select>
</mapper>

Mapper - SysMenuMapper

需要继承 BaseMapper

java 复制代码
package com.vipsoft.admin.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vipsoft.admin.entity.SysMenu;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * 菜单表 数据层
 */
public interface SysMenuMapper extends BaseMapper<SysMenu> {

    List<SysMenu> listMenu(SysMenu menu);

    IPage<SysMenu> listMenuPage(Page page, @Param("query") SysMenu menu);
}

Service

ISysMenuService

java 复制代码
package com.vipsoft.admin.service;


import com.baomidou.mybatisplus.core.metadata.IPage; 
import com.vipsoft.admin.entity.SysMenu; 

import java.util.List; 

/**
 * 菜单 业务层
 *
 */
public interface ISysMenuService
{
    /**
     * 列表查询(自定义SQL,分页)
     */
    List<SysMenu> listMenu(SysMenu menu);

    /**
     * 列表查询(框架分页)
     */
    IPage  selectPage(SysMenu menu);


    /**
     * 列表查询(自定义SQL,分页)
     */
    IPage listMenuPage(SysMenu menu);
}

SysMenuService

java 复制代码
package com.vipsoft.admin.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vipsoft.admin.entity.SysMenu;
import com.vipsoft.admin.mapper.SysMenuMapper;
import com.vipsoft.admin.service.ISysMenuService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 菜单 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysMenuServiceImpl implements ISysMenuService { 

    @Autowired
    private SysMenuMapper menuMapper;

    /**
     * 列表查询(自定义SQL,分页)
     */
    @Override
    public List<SysMenu> listMenu(SysMenu menu) {
        return menuMapper.listMenu(new SysMenu());
    }

    /**
     * 列表查询(框架分页)
     */
    @Override
    public IPage selectPage(SysMenu menu) {
        Page page = new Page();
        page.setCurrent(2);
        page.setSize(10);
        List<OrderItem> orderItems = new ArrayList<>();
        orderItems.add(OrderItem.desc("menu_id"));
        page.setOrders(orderItems);
        Page pageList = menuMapper.selectPage(page, null);
        return pageList;
    }

    /**
     * 列表查询(自定义SQL,分页)
     */
    @Override
    public IPage listMenuPage(SysMenu menu) {
        Page page = new Page();
        page.setCurrent(2);
        page.setSize(10);
        List<OrderItem> orderItems = new ArrayList<>();
        orderItems.add(OrderItem.desc("menu_id")); //先按 menu_id 排序,再按 mapper.xml 中的排(可以在查询输出的SQL中查看)
        page.setOrders(orderItems);
        IPage<SysMenu> pageList = menuMapper.listMenuPage(page, menu);
        return pageList;
    }
}

Controller

java 复制代码
package com.vipsoft.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vipsoft.admin.entity.SysMenu;
import com.vipsoft.admin.service.ISysMenuService;
import com.vipsoft.base.core.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 菜单信息
 */
@RestController
@RequestMapping("/menu")
public class SysMenuController {
    @Autowired
    private ISysMenuService menuService;

    /**
     * 获取菜单列表
     */
    @GetMapping("/selectPage")
    public ApiResult selectPage(SysMenu menu) {
        IPage menus = menuService.selectPage(menu);
        return new ApiResult(menus);
    }

    /**
     * 获取菜单列表
     */
    @GetMapping("/list")
    public ApiResult listMenu(SysMenu menu) {
        List<SysMenu> menus = menuService.listMenu(menu);
        return new ApiResult(menus);
    }


    /**
     * 获取菜单列表
     */
    @GetMapping("/listMenuPage")
    public ApiResult listMenuPage(SysMenu menu) {
        IPage menus = menuService.listMenuPage(menu);
        return new ApiResult(menus);
    }
}
相关推荐
计算机学姐1 小时前
基于协同过滤算法的旅游网站推荐系统
vue.js·mysql·算法·mybatis·springboot·旅游·1024程序员节
ppo_wu12 小时前
关闭kafka在控制台打印的日志
分布式·kafka·springboot
lapiii3581 天前
瑞吉外卖之com.fasterxml.jackson.dataformat.cbor.CBORFactor相关报错
java·springboot
遇见你真好。1 天前
SpringBoot整合quartz定时任务
java·springboot·quartz
VipSoft1 天前
根据字符串,获取实体属性上的annotation,如:createTime” 找到对应实体属性中的 TableField(value = "create_time", fill = FieldFill.INSERT)
springboot
怎么起个名就那么难6 天前
ElasticSearch的向量存储和搜索
大数据·人工智能·spring·elasticsearch·langchain·springboot·springai
尚学教辅学习资料6 天前
基于springboot企业微信SCRM管理系统源码带本地搭建教程
springboot·scrm·java源码·1024程序员节
是小秋吖6 天前
微服务-CAP和AKF拆分原则
java·数据库·spring·spring cloud·微服务·架构·springboot
逐星ing6 天前
分布式并发场景的核心问题与解决方案
java·分布式·spring cloud·springboot·1024程序员节
晨港飞燕7 天前
SpringCloudAlibaba升级手册
springboot·springcloud