【Spring Cloud Alibaba】Mybatis Plus 持久层

1、Mybatis Plus

Mybatis Plus 是国产的持久层框架,这里使用起来就很简单了,应为是中文!

Mybatis Plus 官网:https://baomidou.com/ 在 Spring Cloud Alibaba 中集成的方式和 Spring Boot 是一样的

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  • 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 – Sequence),可自由配置,- 完美解决主键问题
  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
  • 内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

2、集成 Mybatis Plus

创建 spring-cloud-alibaba-mybatis-plus 模块,引入相关依赖,和其他的模块没有什么区别,同样的注册到 Nacos 中

${mybatis-plus-boot-starter.version}
${lombok.version}

版本为

<mybatis-plus-boot-starter.version>3.4.3</mybatis-plus-boot-starter.version>
<lombok.version>1.18.20</lombok.version>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis-plus-boot-starter.version}</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

修改 application.yml 配置文件,为了方便编写,这里使用的是 yml 格式的

# 应用配置
server:
  port: 8006

# 端点监控
management:
  endpoint:
    health:
      show-details: always
  endpoints:
    jmx:
      exposure:
        include: '*'
    web:
      exposure:
        include: '*'
  server:
    port: 9006

spring:
  # 应用名称
  application:
    name: spring-cloud-alibaba-gateway
  # 数据源
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/spring-cloud-alibaba-learn?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
    username: root
    password: 123456
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
    serialization:
      write-dates-as-timestamps: false
  # Nacos配置
  cloud:
    nacos:
      discovery:
        namespace: sandbox-configuration
        password: nacos
        server-addr: localhost:8848
        username: nacos

# MybatisPlus配置
mybatis-plus:
  configuration:
    map-underscore-to-camel-case: true
    auto-mapping-behavior: full
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath*:mapper/**/*Mapper.xml
  global-config:
    # 逻辑删除配置
    db-config:
      # 删除前
      logic-not-delete-value: 1
      # 删除后
      logic-delete-value: 2

启动类增加

@EnableDiscoveryClient

创建控制层

package cn.tellsea.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户表 前端控制器
 *
 * @author Tellsea
 * @since 2021-12-28
 */

@RestController
@RequestMapping("/userInfo")
public class UserInfoController {

}

创建接口

package cn.tellsea.service;

import cn.tellsea.entity.UserInfo;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * 用户表 服务类
 *
 * @author Tellsea
 * @since 2021-12-28
 */

public interface IUserInfoService extends IService<UserInfo{

}

创建接口实现类

package cn.tellsea.service.impl;

import cn.tellsea.entity.UserInfo;
import cn.tellsea.mapper.UserInfoMapper;
import cn.tellsea.service.IUserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * 用户表 服务实现类
 *
 * @author Tellsea
 * @since 2021-12-28
 */

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapperUserInfoimplements IUserInfoService {

}

创建 Mapper

package cn.tellsea.mapper;

import cn.tellsea.entity.UserInfo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * Mapper 接口
 *
 * @author Tellsea
 * @since 2021-12-28
 */

public interface UserInfoMapper extends BaseMapper<UserInfo{

}

在 resources/mapper 下面创建 Mapper.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="cn.tellsea.mapper.UserInfoMapper">

    <!-- 自定义SQL -->

</mapper>

创建 Mybatis Plus 注入器,补全字段

package cn.tellsea.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * MybatisPlus注入处理器
 *
 * @author Tellsea
 * @date 2021/12/28
 */

public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasGetter("createTime")) {
            if (metaObject.getValue("createTime") == null) {
                this.setFieldValByName("createTime"new Date(), metaObject);
            }
        }
        if (metaObject.hasGetter("createBy")) {
            if (metaObject.getValue("createBy") == null) {
                this.setFieldValByName("createBy""当前登录的用户名", metaObject);
            }
        }
        this.setFieldValByName("status"1, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasGetter("updateBy")) {
            if (metaObject.getValue("updateBy") == null) {
                this.setFieldValByName("updateBy""当前登录的用户名", metaObject);
            }
        }
        if (metaObject.hasGetter("updateTime")) {
            if (metaObject.getValue("updateTime") == null) {
                this.setFieldValByName("updateTime"new Date(), metaObject);
            }
        }
    }

}

创建单元测试

package cn.tellsea;

import cn.tellsea.entity.UserInfo;
import cn.tellsea.service.IUserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.List;

/**
 * 单元测试
 *
 * @author Tellsea
 * @date 2021/12/28
 */

@SpringBootTest
class SpringCloudAlibabaMybatisPlusApplicationTests {

    @Autowired
    private IUserInfoService userInfoService;

    @Test
    void contextLoads() {
    }

    @Test
    public void test() {
        UserInfo entity = new UserInfo();
        List<UserInfo> userInfoList = new ArrayList<>();

        // 新增
        userInfoService.save(entity);

        // 批量新增
        userInfoService.saveBatch(userInfoList);

        // 根据ID更新
        userInfoService.updateById(entity);

        // 根据ID批量更新
        userInfoService.updateBatchById(userInfoList);

        // 根据ID删除
        userInfoService.removeById(entity.getId());

        // 查询所有
        userInfoService.list();

        // 条件查询
        userInfoService.list(new LambdaQueryWrapper<UserInfo>()
                .like(UserInfo::getUserName, entity.getUserName()));
    }

}

这些代码可以通过 Mybatis Plus 的代码生成器一次性生成的,本篇文章主要说明 Mybatis Plus 在 SpringCloud Alibaba 中的使用和在 Spring Boot 中的使用是一样的。Mybatis Plus 的代码生成器会在相对应的模块更新,并具体说明使用方法,和定制模板

微信公众号


原文始发于微信公众号(花海里):【Spring Cloud Alibaba】Mybatis Plus 持久层

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/69459.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!