其他分享
首页 > 其他分享> > 【Spring Cloud Alibaba】Mybatis Plus 持久层

【Spring Cloud Alibaba】Mybatis Plus 持久层

作者:互联网

文章目录

【Spring Cloud Alibaba】Mybatis Plus 持久层

1、Mybatis Plus

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

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

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<UserInfoMapper, UserInfo> implements 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 的代码生成器会在相对应的模块更新,并具体说明使用方法,和定制模板

微信公众号

标签:tellsea,metaObject,cn,Spring,Alibaba,Plus,org,Mybatis,import
来源: https://blog.csdn.net/qq_38762237/article/details/122197053