Springboot集成Mybatispuls操作mysql数据库-04

ops/2024/9/20 13:43:04/ 标签: 数据库, spring boot, mysql

MyBatis-Plus(简称MP)是一个MyBatis的增强工具,在MyBatis的基础上只做增强而不做改变。它支持所有MyBatis原生的特性,因此引入MyBatis-Plus不会对现有的MyBatis构架产生任何影响。MyBatis-Plus旨在简化开发、提高效率,特别是简化了CRUD(增删改查)操作。

MyBatis常见使用场景

  1. 数据权限控制:在查询数据时,自动添加当前用户可访问的数据范围的WHERE条件。
  2. 多租户支持:在查询数据时,自动添加租户ID的WHERE条件,以区分不同租户的数据。
  3. 动态表名:根据不同的请求参数,动态修改SQL语句中的表名,以实现数据分片或数据隔离等功能。
  4. 加密解密:对数据库中的敏感数据进行加密,查询数据时进行解密。
  5. 缓存优化:通过缓存某些查询结果来提高系统性能,可以将缓存对象作为拦截器的属性来管理。

MyBatis-Plus通过启动加载XML配置时注入单表SQL操作来简化开发工作,提高生产率。总的来说,MyBatis-Plus是一个强大的MyBatis增强工具,为开发者提供了更多的便利和灵活性。

springboot-mybatisplus模块

在此模块中我们会通过springbootTest和Controller两种方式来进行测试。

模块结构说明

在这里插入图片描述

  • 类文件说明

    • SystemLogController.java:controller,它会调用ISystemLogDao接口
    • ISystemLogDao.java:Dao接口
    • SystemLogQuery:ISystemLogDao接口参数
    • SystemLogDaoImpl.java:ISystemLogDao接口实现
    • SystemLogMapper.java:mybatis Mapper接口
    • SystemLogEntity.java:数据库实体类
  • 文件夹

    • resources/mybatis:mybatis配置文件,一般与SystemLogMapper.java一一对应
  • 测试类

    • SystemLogControllerTest:测试 LoadBalanceController.java URI接口功能
    • SystemLogDaoTest:测试 ISystemLogDao.java 接口实现功能

数据库脚本

数据库脚本

需要事先导入到数据库

CREATE TABLE `jdemo`.`t_sys_record_demo`  (`uuid` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,`biz_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '业务ID',`user_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '操作用户ID',`track_uid` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '链路ID',`code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '操作代码',`custom_code` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '操作2级代码',`status` int NULL DEFAULT NULL COMMENT '记录状态:1可查询,0不可查询',`ctime` datetime NULL DEFAULT NULL,`utime` datetime NULL DEFAULT NULL,`cid` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,`cname` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,PRIMARY KEY (`uuid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

java实体类

注意下列@TableName中的值要和数据库表名一致。

@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("t_sys_record_demo")
public class SystemLogEntity extends DBEntity {private String bizId;private String userId;private String trackUid;private String code;private String customCode;private Integer status;@TableField(value = "cid", fill = FieldFill.INSERT, insertStrategy = FieldStrategy.NEVER, updateStrategy = FieldStrategy.NEVER)private String cid;@TableField(value = "cname", fill = FieldFill.INSERT, insertStrategy = FieldStrategy.NEVER, updateStrategy = FieldStrategy.NEVER)private String cname;}

模块配置

pom.xml

这里需要注意mybatisplus分2和3两个版本,3版本对应的springboot3,2对应的是springboot2,这两个mybatisplus版本并不兼容。

    <dependencies><!--数据库相关--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-spring-boot3-starter</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId></dependency><!--工具包--><dependency><groupId>com.korgs</groupId><artifactId>framework-persistence</artifactId><version>1.0-SNAPSHOT</version></dependency></dependencies>

framework-persistence是笔者开发的一个基础jar包,在源码中可以找到。

Invalid value type for attribute ‘factoryBeanObjectType’: java.lang.String 这个错误是由于版本不对引起的, 因为mybatis2和3不相互兼容,这主要是jdk版本不同导致的,其它三方插件也有这个问题。

application.properties配置

spring.profiles.active = dev
spring.application.name=springbootMybatisplus
server.port=18086
#debug=truemanagement.endpoints.web.exposure.include = *
management.endpoint.health.show-details=always##mybatis Server
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/jdemo?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=12345678
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20
spring.datasource.druid.max-wait=60000
spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=5
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=100000
spring.datasource.druid.filters=stat
#
##mybatis plugs
mybatis-plus.mapper-locations=classpath:/mybatis/*Mapper.xml
mybatis-plus.configuration.map-underscore-to-camel-case=true
mybatis-plus.configuration.default-statement-timeout=20000
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

注意:上面配置中的mybatis-plus.configuration.log-implmybatis-plus.mapper-locations。前者用于日志打印,在发布应用时需要注释掉,后者用来指定Mapper.xml文件存放的classpath地址。

SpringbootApplication启动类

配置@MapperScan注解,比如@MapperScan("com.korgs.dao")表示要查找的mybatis bean类。

@Slf4j
@SpringBootApplication(scanBasePackages = {"com.korgs",  "cn.hutool.extra.spring"})
@Configuration
@EnableConfigurationProperties
@ServletComponentScan
@RestController
@MapperScan("com.korgs.dao")
public class SpringbootMybatisplusApplication {public static void main(String[] args) {SpringApplication.run(SpringbootMybatisplusApplication.class, args);}@GetMapping("/helloworld")public BaseResponse helloWorld(){log.info(LogGenerator.trackLog()+ "msg="+ "I am busy to handle this request.");return BaseResponse.success("hello world");}
}

程序实现

定义ISystemLogDao接口

定义供上层类调用的数据库操作接口
在这里插入图片描述

接口定义
public interface ISystemLogDao extends IService<SystemLogEntity> {List<SystemLogEntity> listByCondition(SystemLogQuery query);IPage<SystemLogEntity> pageSystemLog(IPage<SystemLogEntity> iPage, String bizId, String code);
}
接口实现
@Repository
@Primary
public class SystemLogDaoImpl extends ServiceImpl<SystemLogMapper, SystemLogEntity> implements ISystemLogDao {@Overridepublic List<SystemLogEntity> listByCondition(SystemLogQuery query) {LambdaQueryWrapper<SystemLogEntity> queryWrapper = Wrappers.lambdaQuery();if(StrUtil.isNotEmpty(query.getCode())){queryWrapper.eq(SystemLogEntity::getCode, query.getCode());}if(StrUtil.isNotEmpty(query.getBizId())){queryWrapper.eq(SystemLogEntity::getBizId, query.getBizId());}return list(queryWrapper);}@Overridepublic IPage<SystemLogEntity> pageSystemLog(IPage<SystemLogEntity> iPage, String bizId, String code) {return this.getBaseMapper().pageSystemLog(iPage, bizId, code);}}
接口参数
@Data
public class SystemLogQuery {private String bizId;private String code;
}

定义Mapper实现

一个Mapper实现类对应一个Mapper.xml,即使Mapper.xml为空实现也需要配置。

Mapper接口定义
public interface SystemLogMapper extends BaseMapper<SystemLogEntity> {IPage<SystemLogEntity> pageSystemLog(IPage<SystemLogEntity> iPage,@Param("bizId") String bizId,@Param("code") String code);
}
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="com.korgs.dao.SystemLogMapper"><select id="pageSystemLog" resultType="com.korgs.dao.SystemLogEntity">selectt_sys_record_demo.*fromt_sys_record_demowhere 1=1<if test="bizId != null">and t_sys_record_demo.biz_id = #{bizId}</if><if test="code != null">and upper(t_sys_record_demo.code) LIKE upper(CONCAT('%',#{code},'%'))</if></select>
</mapper>

上述配置文件中:

  • mapper标签:配置为SystemLogMapper.java类的全路径
  • select标签中的id属性:配置为SystemLogMapper.java类中定义的接口名称
    • select标签中的resultType属性:定义为sql语句要返回的实体对象的全路径,此值也与SystemLogMapper.java中相应的接口返回参数相对应。

编写Controller Restful

@Slf4j
@RestController
@RequestMapping("/api/load")
public class SystemLogController {@Autowiredprivate ISystemLogDao iSystemLogDao;@GetMapping("/v1/hello-content")public ListResponse<SystemLogEntity> loadHelloContent(String uuid){log.info("{} uuid ={}", LogGenerator.trackLog(), uuid);List<SystemLogEntity> list = iSystemLogDao.list();log.info("{} uuid={} size={}", LogGenerator.trackLog(), uuid, CollUtil.size(list));return ListResponse.success(list);}
}

使用SpringbootTest测试

测试Dao接口

@SpringBootTest
public class SystemLogDaoTest {private static final Logger logger = LoggerFactory.getLogger(SystemLogDaoTest.class);@Autowiredprivate ISystemLogDao iSystemLogDao;/*注意此处要引用 import org.junit.jupiter.api.Test;*//*全表搜索*/@Testpublic void iSystemLogDao() {List<SystemLogEntity> list = iSystemLogDao.list();logger.info(JSONUtil.toJsonStr(list));}/*增加操作*/@Testpublic void iSystemLogDaoInsert() {SystemLogEntity systemLogEntity = new SystemLogEntity();systemLogEntity.setUuid(UUIDUtil.uuid32());iSystemLogDao.save(systemLogEntity);}/*删除操作*/@Testpublic void iSystemLogDaoDelete() {iSystemLogDao.removeById("3006316502a24b6b8b5eac4d1a8f6e5a");}/*更新操作*/@Testpublic void iSystemLogDaoUpdate() {SystemLogEntity systemLogEntity = new SystemLogEntity();systemLogEntity.setUuid("a4dd3bcf2a134941a4a1fb9119028600");systemLogEntity.setCode("heart");iSystemLogDao.updateById(systemLogEntity);}/*分页查询*/@Testpublic  void iSystemLogDaoPage() {IPage<SystemLogEntity> iPage = new Page<SystemLogEntity>(1, 3);iPage = iSystemLogDao.pageSystemLog(iPage, "001", "lung");List<SystemLogEntity>  logEntityIPage = iPage.getRecords();logger.info(JSONUtil.toJsonStr(logEntityIPage));}}

测试Controller服务

@SpringBootTest
@AutoConfigureMockMvc
public class SystemLogControllerTest {@Autowiredprotected MockMvc mockMvc;private HttpHeaders httpHeaders = new HttpHeaders();private static final ObjectMapper mapper = new ObjectMapper();//    @Beforepublic void setBasicAuth() throws Exception {// 设置basicAuthString basicAuthString = "Basic " + Base64.getEncoder().encodeToString("aaa:bbb".getBytes());httpHeaders.set("Authorization", basicAuthString);}@Testpublic void testController() throws Exception {MvcResult mvcResult = mockMvc.perform(get("/api/load//v1/hello-content").contentType(MediaType.APPLICATION_JSON_VALUE)// 设定basicAuth到请求header中.headers(httpHeaders).param("uuid", "12312312"))// 打印详细的请求以及返回内容.andDo(print())// 判断HttpStatus是200,如果不是表示失败.andExpect(status().isOk())// 返回结果给mvcResult.andReturn();// 获取mvcResult的bodyString resutlStr = mvcResult.getResponse().getContentAsString(Charset.defaultCharset());ListResponse response =  mapper.readValue(resutlStr, ListResponse.class);// 判断结果是否成功assertEquals("0", response.getStatus().toString());}}

源码下载

涉及模块:

  • springboot-mybatisplus:18086

源码下载:

  • 着手开发属于自己的第一个Intellij-platform plugin插件程序(三)配套源码
  • Springboot集成Mybatispuls操作mysql数据库

源码运行方法:

  • SpringCloud专题模块项目功能说明和运行方法

http://www.ppmy.cn/ops/40765.html

相关文章

TCP(TCP客户端、服务器如何通信)

一、TCP介绍 TCP的特点&#xff1a; 面向连接的协议&#xff1a;TCP是一种可靠的、面向连接的协议&#xff0c;在通信之前需要建立连接&#xff0c;以确保数据的可靠传输。这意味着在传输数据之前&#xff0c;发送方和接收方之间需要建立一条可靠的连接通道。流式协议&#x…

Redis常用语法命令及使用示例详解

点击下载《Redis常用语法命令及使用示例详解》 Redis 是一个开源的内存数据结构存储系统&#xff0c;它可以用作数据库、缓存和消息中介。它支持多种类型的数据结构&#xff0c;如字符串、哈希、列表、集合、有序集合等类型&#xff0c;并且提供了丰富的命令来进行数据的增删改…

MySQL 数据库事务 ACID 特性

什么是数据库事务 将一些对数据库的操作组成一个集合&#xff0c;这个集合就是事务。事务的特点&#xff0c;包含在内的操作要么都执行&#xff0c;要么都失败。 关于事务经典的问题就是金融转账了&#xff0c;小明要向小红转账1000元&#xff0c;转账的过程中包含了以下操作…

Reactor Netty TCP 服务器端-响应式编程-011

🤗 ApiHug {Postman|Swagger|Api...} = 快↑ 准√ 省↓ GitHub - apihug/apihug.com: All abou the Apihug apihug.com: 有爱,有温度,有质量,有信任ApiHug - API design Copilot - IntelliJ IDEs Plugin | Marketplace The Next Generation API Development Platform…

大模型微调方法汇总

微调方法 Freeze方法P-tuning方法 prefix-tuningPrompt TuningP-tuning v1P-tuning v2Lora方法 重要相关参数LoRA 的优势Qlora方法 相关参数微调经验 模型选择模型大小选择数据处理微调方案英文模型需要做词表扩充吗&#xff1f;如何避免灾难遗忘大模型的幻觉问题微调后的输出…

一起了解开源自定义表单的优势表现

随着社会的进步和科技的发展&#xff0c;越来越多的中小企业希望采用更为先进的软件平台&#xff0c;助力企业实现高效率的流程化管理。低代码技术平台、开源自定义表单已经慢慢走入大众视野&#xff0c;成为一款灵活、高效的数字化转型工具。流辰信息专注于低代码技术平台的研…

【论文阅读】<YOLOP: You Only Look Once for PanopticDriving Perception>

Abstract 全视驾驶感知系统是自动驾驶的重要组成部分。一个高精度的实时感知系统可以帮助车辆在驾驶时做出合理的决策。我们提出了一个全视驾驶感知网络&#xff08;您只需寻找一次全视驾驶感知网络&#xff08;YOLOP&#xff09;&#xff09;&#xff0c;以同时执行交通目标检…

【退役之重学Java】关于 Redis

一、Redis 都有哪些数据类型 String 最基本的类型&#xff0c;普通的set和get&#xff0c;做简单的kv缓存hash 这是一个类似map 的一种结构&#xff0c;这个一般可以将结构化的数据&#xff0c;比如一个对象&#xff08;前提是这个对象没有嵌套其他的对象&#xff09;给缓存在…

es6语法总结

【1】语法 &#xff08;1&#xff09;声明变量(let-var-const) 变量提升&#xff1a; 是JavaScript引擎在代码执行前将变量的声明部分提升到作用域顶部的行为。尽管变量的声明被提升了&#xff0c;变量的赋值&#xff08;即初始化&#xff09;仍然保留在原来的位置。因此&…

1-3 如何学习,才能让这门课真正发挥价值

如何学习&#xff0c;才能让这门课真正发挥价值 在正式踏上产品经理学习之路前。我希望以一名课程产品经理的身份&#xff0c;来向你解释下这门课的设计理念和学习方法&#xff0c;以便让它真正对你有所帮助。 为什么这么说呢&#xff1f;是因为我发现&#xff0c;大都具备非常…

13.跳跃游戏

文章目录 题目简介题目解答解法一&#xff1a;贪心算法&#xff0b;动态规划代码&#xff1a;复杂度分析&#xff1a; 题目链接 大家好&#xff0c;我是晓星航。今天为大家带来的是 跳跃游戏面试题 相关的讲解&#xff01;&#x1f600; 题目简介 题目解答 思路&#xff1a;这…

BUG:PyAutoGUI pyautogui.ImageNotFoundException

BUG:PyAutoGUI pyautogui.ImageNotFoundException 环境 python 3.10 PyAutoGUI0.9.54 PyScreeze0.1.30BUG详情 在确定屏幕存在指定图片的情况下&#xff0c;使用PyAutoGUI中的locateCenterOnScreen()函数识别图片失败弹出这个bug。 注意&#xff1a; 1 如果屏幕不存在指定图…

电影网站|基于SSM+vue的电影网站系统(源码+数据库+文档)

电影网站 目录 基于SSMvue的电影网站系统 一、前言 二、系统设计 三、系统功能设计 1 系统功能模块 2 管理员功能模块 四、数据库设计 五、核心代码 六、论文参考 七、最新计算机毕设选题推荐 八、源码获取&#xff1a; 博主介绍&#xff1a;✌️大厂码农|毕设布道…

IT行业现状与未来趋势

你眼中的IT行业现状与未来趋势 IT行业当前处于高速发展阶段&#xff0c;涵盖了各种技术领域&#xff0c;如人工智能、大数据、云计算、物联网、区块链等。以下是我眼中的一些现状和未来趋势&#xff1a; 1. 人工智能&#xff08;AI&#xff09;的普及和应用广泛化&#xff1a…

一次pytorch分布式训练精度调试过程

现象: loss不下降 过程如下: 1.减少层数&#xff0c;准备最小复现环境 2.dropout设置为0&#xff0c;重复运行二次&#xff0c;对比loss是否一致 3.第二次迭代开始loss不一致 4.对比backward之后的梯度,发现某一个梯度不一致 5.dump得到所有算子的规模&#xff0c;单算子测试…

Cocos Creator 3.8.x报错:5302

在小游戏加载某个bundle后&#xff0c;如果报以下错误&#xff1a; 5302&#xff1a;Can not find class %s 说明bundle中某个预制件*.prefab引用了未加载的bundle的资源。 解决方法有两个&#xff1a; 1、将引用的资源移到预制件*.prefab相同的bundle下&#xff1b; 2、将…

三极管 导通条件

一、三极管理解 三极管是电子行业常用的元器件之一&#xff0c;他是一种电流型控制的器件&#xff0c;他有三种工作状态&#xff1a;截止区&#xff0c;放大区、饱和区。当三极管当做开关使用时&#xff0c;他工作在饱和区。下面简短讲解三极管作为开关使用的方法&#xff0c;只…

OpenMVS学习笔记(一):WSL编译安装测试

1.CUDA和CUDNN安装 [1] WSL版本cuda安装&#xff1a; >> wget https://developer.download.nvidia.com/compute/cuda/repos/wsl-ubuntu/x86_64/cuda-wsl-ubuntu.pin >> sudo mv cuda-wsl-ubuntu.pin /etc/apt/preferences.d/cuda-repository-pin-600 >> wg…

Redis 基础之Redis 配置

Redis 配置 Redis CONFIG GET 命令语法格式编辑配置Redis 配置参数说明 Redis 提供了很多配置选项来优化 Redis 服务 Redis 的配置文件位于 Redis 安装目录下&#xff0c;文件名为 redis.conf 可以通过 Redis CONFIG 命令查看或设置配置项 Redis CONFIG GET 命令语法格式 Re…

【Python技术】使用akshare、pandas高效复盘每日涨停板行业分析

作为一个程序员宝爸&#xff0c;每天的时间很宝贵&#xff0c;工作之余除了辅导孩子作业&#xff0c;就是补充睡眠。 怎么快速高效的进行当天A股涨停板的复盘&#xff0c;便于第二天的跟踪。这里简单写个示例&#xff0c; 获取当天连涨数排序&#xff0c;以及所属行业排序。 …