当前位置: 首页 > news >正文

MyBatis Plus基本用法-SpringBoot框架

依赖

使用 Mybatis Plus 框架时,需要添加以下依赖:

<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>latest-version</version>
</dependency>

其中,latest-version 为最新版本号,可以在官网或 Maven 仓库中查看。

此外,还需要添加与所使用的数据库连接相关的依赖。例如,如果使用 MySQL 数据库,需要添加以下依赖:

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

如果使用 Oracle 数据库,需要添加以下依赖:

<dependency><groupId>com.oracle.database.jdbc</groupId><artifactId>ojdbc8</artifactId><version>19.3.0.0</version>
</dependency>

如果使用 PostgreSQL 数据库,需要添加以下依赖:

<dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId><version>42.2.23</version>
</dependency>

如果使用 SQL Server 数据库,需要添加以下依赖:

<dependency><groupId>com.microsoft.sqlserver</groupId><artifactId>mssql-jdbc</artifactId><version>9.4.0.jre11</version>
</dependency>

这些依赖可以根据实际需要进行选择和配置。

1. XML文件代码注释说明

数据库表生成

首先需要在数据库中创建一个user表,表结构如下:

CREATE TABLE `user` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`name` varchar(20) NOT NULL,`age` int(11) NOT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Mybatis Plus的增删改查

下面是使用XML文件进行增删改查操作的示例代码:

<!-- UserMapper.xml --><mapper namespace="com.example.mapper.UserMapper"><!-- 新增数据 --><insert id="insertUser" parameterType="com.example.entity.User">INSERT INTO user(name, age) VALUES (#{name}, #{age})</insert><!-- 根据id查询数据 --><select id="selectUserById" resultType="com.example.entity.User">SELECT * FROM user WHERE id = #{id}</select><!-- 更新数据 --><update id="updateUser" parameterType="com.example.entity.User">UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}</update><!-- 根据id删除数据 --><delete id="deleteUserById">DELETE FROM user WHERE id = #{id}</delete><!-- 多表关联分组查询 --><select id="selectUserOrderCount" resultType="com.example.entity.UserOrderCount">SELECT u.name, u.age, COUNT(o.id) as order_count FROM user uLEFT JOIN `order` o ON u.id = o.user_idGROUP BY u.id</select><!-- 视图查询 --><select id="selectUserViewList" resultType="com.example.entity.UserView">SELECT * FROM user_view</select><!-- 存储过程查询 --><select id="callGetUserCount" statementType="CALLABLE" parameterType="java.util.Map">{CALL getUserCount(#{age, mode=IN, jdbcType=INTEGER}, #{count, mode=OUT, jdbcType=INTEGER})}</select></mapper>

2. Mapper文件代码注释

下面是使用Mapper文件调用上述方法的示例代码:

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;import java.util.List;
import java.util.Map;@Mapper
public interface UserMapper {// 新增数据void insertUser(User user);// 根据id查询数据User selectUserById(Long id);// 更新数据void updateUser(User user);// 根据id删除数据void deleteUserById(Long id);// 多表关联分组查询List<UserOrderCount> selectUserOrderCount();// 视图查询List<UserView> selectUserViewList();// 调用存储过程查询void callGetUserCount(Map<String, Object> paramMap);
}

3. SQL脚本

下面是提供相关建表、建视图、建存储过程和数据插入的SQL脚本:

-- 创建user表
CREATE TABLE `user` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`name` varchar(20) NOT NULL,`age` int(11) NOT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;-- 创建order表
CREATE TABLE `order` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`order_no` varchar(50) NOT NULL,`user_id` bigint(20) NOT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;-- 创建user_view视图
CREATE VIEW `user_view` AS 
SELECT u.name, u.age, COUNT(o.id) as order_count FROM user u 
LEFT JOIN `order` o ON u.id = o.user_id 
GROUP BY u.id;-- 创建存储过程getUserCount
CREATE PROCEDURE `getUserCount`(IN age INT, OUT count INT)
BEGINSELECT COUNT(*)INTO countFROM userWHERE age = age;
END;-- 插入测试数据
INSERT INTO user(name, age) VALUES ('张三', 18);
INSERT INTO user(name, age) VALUES ('李四', 20);
INSERT INTO user(name, age) VALUES ('王五', 22);INSERT INTO `order`(order_no, user_id) VALUES ('202201010001', 1);
INSERT INTO `order`(order_no, user_id) VALUES ('202201010002', 1);
INSERT INTO `order`(order_no, user_id) VALUES ('202201010003', 2);
INSERT INTO `order`(order_no, user_id) VALUES ('202201010004', 3);

4. YML文件代码注释说明

下面是使用YML文件进行Mybatis Plus的详细全面的配置的示例代码:

mybatis-plus:# mapper文件的路径mapper-locations: classpath:/mapper/*.xml# 实体类的包路径typeAliasesPackage: com.example.entityconfiguration:# 配置驼峰命名规则map-underscore-to-camel-case: true# 配置缓存cache-enabled: true# 配置多数据源# dataSource: com.baomidou.mybatisplus.spring.boot.starter.jdbc.MybatisPlusProperties$Druidglobal-config:# 配置逻辑删除字段db-config:logic-delete-field: deletedlogic-delete-value: 1logic-not-delete-value: 0# 配置分页插件page-helper:auto-dialect: truereasonable: truesupport-methods-arguments: true

5. Java文件代码注释

下面是使用Java文件进行实体类的示例代码:

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;@Data
@TableName("user")
public class User {@TableId(value = "id", type = IdType.AUTO)private Long id;@TableField("name")private String name;@TableField("age")private Integer age;}
import lombok.Data;@Data
public class UserOrderCount {private String name;private Integer age;private Integer orderCount;}
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;@Data
public class UserView {@TableField("name")private String name;@TableField("age")private Integer age;@TableField("order_count")private Integer orderCount;}

下面是使用Java文件进行Service和Controller的示例代码:

import com.baomidou.mybatisplus.extension.service.IService;public interface UserService extends IService<User> {void addUser(User user);User getUserById(Long id);void updateUser(User user);void deleteUserById(Long id);List<UserOrderCount> getUserOrderCount();List<UserView> getUserViewList();Integer getUserCountByAge(Integer age);}
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {@Overridepublic void addUser(User user) {baseMapper.insertUser(user);}@Overridepublic User getUserById(Long id) {return baseMapper.selectUserById(id);}@Overridepublic void updateUser(User user) {baseMapper.updateUser(user);}@Overridepublic void deleteUserById(Long id) {baseMapper.deleteUserById(id);}@Overridepublic List<UserOrderCount> getUserOrderCount() {return baseMapper.selectUserOrderCount();}@Overridepublic List<UserView> getUserViewList() {return baseMapper.selectUserViewList();}@Overridepublic Integer getUserCountByAge(Integer age) {Map<String, Object> paramMap = new HashMap<>();paramMap.put("age", age);paramMap.put("count", null);baseMapper.callGetUserCount(paramMap);return (Integer) paramMap.get("count");}}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;@PostMapping("/add")public String addUser(@RequestBody User user) {userService.addUser(user);return "添加成功";}@GetMapping("/{id}")public User getUserById(@PathVariable Long id) {return userService.getUserById(id);}@PutMapping("/update")public String updateUser(@RequestBody User user) {userService.updateUser(user);return "更新成功";}@DeleteMapping("/{id}")public String deleteUserById(@PathVariable Long id) {userService.deleteUserById(id);return "删除成功";}@GetMapping("/orderCount")public List<UserOrderCount> getUserOrderCount() {return userService.getUserOrderCount();}@GetMapping("/viewList")public List<UserView> getUserViewList() {return userService.getUserViewList();}@GetMapping("/countByAge")public Integer getUserCountByAge(@RequestParam Integer age) {return userService.getUserCountByAge(age);}}

以上代码仅供参考,具体实现方式根据实际情况而定。

相关文章:

MyBatis Plus基本用法-SpringBoot框架

依赖 使用 Mybatis Plus 框架时&#xff0c;需要添加以下依赖&#xff1a; <dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>latest-version</version> </dependency…...

指针--指针变量的定义和初始化

存放变量的地址需要一种特殊类型的变量&#xff0c;这种特殊的数据类型就是指针&#xff08;Pointer&#xff09;。 具有指针类型的变量&#xff0c;称为指针变量&#xff0c;它时专门用于存储变量的地址值和变量。 其定义形式如下&#xff1a; 类型关键字 * 指针变量名&#x…...

Web基本概念

一、前言 World Wide Web的简称&#xff0c;是一个由许多互相链接的超文本组成的系统&#xff0c;通过互联网访问 &#xff08;为用户提供信息&#xff09; 静态网页 仅适用于不能经常更改内容的网页&#xff1b; 动态网页 网络编程技术创建的页面&#xff1b;通过在传统的静态…...

Niagara—— Texture Sample 与 Particle Subuv 区别

目录 一&#xff0c;Texture Sample 二&#xff0c;Particle Subuv 一&#xff0c;Texture Sample 此节点是最基本的采样节点&#xff0c;依据UV坐标来采样Texture&#xff1b; MipValueMode&#xff0c;设置采样的Mipmap Level&#xff1b; None&#xff0c;根据当前Texture…...

如何在食品行业运用IPD?

食品是我国重要的民生产业之一&#xff0c;是保障和满足人民群众不断增长消费需求的重要支撑。食品指各种供人食用或者饮用的成品和原料以及按照传统既是食品又是药品的物品&#xff0c;包括加工食品&#xff0c;半成品和未加工食品&#xff0c;不包括烟草或只作药品用的物质。…...

如何用pandas进行条件分组计算?

Pandas提供了强大的分组聚合功能&#xff0c;可以轻松进行条件分组计算和统计。本文通过一个例子&#xff0c;展示如何使用Pandas的.groupby()和.agg()方法进行条件分组计算。 准备数据 假设有这样一个字典数据: dict { 姓名: [张三&#xff0c;李四&#xff0c;王五&#x…...

tomcat如何调优,涉及哪些参数?

Tomcat是一个流行的开源Java Servlet容器&#xff0c;用于部署和管理Java Web应用程序。调优Tomcat可以提高性能、并发处理能力和稳定性。以下是一些常见的Tomcat调优参数和技巧&#xff1a; 1.调整内存参数&#xff1a; -Xms&#xff1a;指定Tomcat启动时的初始堆内存大小。 -…...

java培训机构学校教学教务选课管理平台springboot+vue

近年来&#xff0c;随着培训机构机构规模的逐渐增大&#xff0c;人工书写的方式已经不能满足如此庞大的数据。为了更好的适应信息时代的高效性&#xff0c;一个利用计算机来实现培训机构教务管理工作的系统将必然诞生。基于这一点&#xff0c;设计了一个培训机构教务管理系统&a…...

半导体(TSS)放电管的两大选购注意事项及选型小策略

固体放电管&#xff0c;是以半导体工艺制作而成的&#xff0c;因此我们也称为半导体&#xff08;TSS&#xff09;放电管&#xff0c;它常在电路中并联使用&#xff0c;具备伏安特性。 TSS放电管在电路中类似开关&#xff0c;在正常工作时不动作&#xff0c;但一般被保护电路受到…...

05-使用Vue3 + Vue CLI 实现前端模块的搭建

1、环境准备 流程:安装node得到npm,使用npm安装vue cli(脚手架),使用vue cli创建项目。 Vue CLI版本和Node版本有关,用Node V12只能下载到Vue CLI V4.X,必须用Node V18才能下载到Vue CLI V5.X IDEA支持配置多个版本的Node,类似配置多个JDK。 node.js安装 1、官网下载…...

3.1 增加多进程执行playwright

增加了多进程的方式执行测试代码&#xff0c;对代码改动比较大 1、case case目录依然是自动生成 2、config dir_collection.py新增了配置 mkdir_collections [case,log,img, ] del_collections [results,report ] del_regex temp3、data/img/log/resource/video data/im…...

关于单片机的时钟浅谈及STM32F103/F030单片机的内外时钟切换问题

绪论 本文主要讲解单片机的时钟系统的相关知识&#xff0c;并进行超频测试&#xff0c;同时介绍如何在STM32F0单片机上进行内外时钟的切换&#xff0c;在不使用外部晶振或者外部晶振不启动时自动切换内部时钟的方法。 一、杂谈 问题来源于群里的一次问答&#xff1a; 诚然&…...

centos6.10环境下安装php7.4(基于WLNMP包)

centos6系统已经被官网停止维护&#xff0c;要安装软件必须用第三方的RPM包&#xff0c;下面使用yum安装php7.4正式版&#xff0c;当前基于WLNMP提供的一键安装包来安装 1、添加epel源 yum install epel-release yum install epel-release 2、添加WLNMP一键安装包源 rpm -iv…...

Qt使用第三方库openssl进行RSA加密解密操作详解

一、openssl库的编译,可以参考文档: https://blog.csdn.net/liang19890820/article/details/51658574/ 因为我这里使用的是windows操作系统,可以直接下载exe格式的安装文件,直接安装即可,就包含了我们需要的头文件和库文件,省去了编译操作。exe安装文件下载地址: htt…...

激发数学思维:GPT-4实证研究探索挑战性数学问题

深度学习自然语言处理 原创作者&#xff1a;wkk 考虑到自然语言在许多科学和工程领域表达的数学问题的丰富性&#xff0c;使用大语言模型(LLM)来解决数学问题是一项有趣的研究工作。今天给大家介绍一篇微软研究院联合欧美高校关于如何使用GPT-4解决数学问题的研究论文。 之前的…...

如何配置IP地址

一.自动获取IP 1.dhclient 2.ifconfig 通过这个命令可以查看系统有几块网卡和网卡的IP。 如果您的Linux有多块网卡&#xff0c;那么在Linux中它会显示成eth1, eth2 依此类推 二.手动配置IP 如果您的虚拟机不能自动获取IP&#xff0c;那么只能手动配置&#xff0c;配置方法为&am…...

CentOS + Nginx 环境自动申请和部署Let‘s Encrypt免费SSL证书教程

文章目录 步骤 1&#xff1a;安装Certbot工具步骤 2&#xff1a;配置Nginx服务器步骤 3&#xff1a;生成SSL证书步骤 4&#xff1a;配置Nginx以使用SSL证书步骤 5&#xff1a;重新加载Nginx配置步骤 6&#xff1a;自动续期证书 本文介绍如何在 CentOS Nginx 环境下&#xff0c…...

浅谈对BI工具价值的看法

浅谈对BI工具价值的看法 BI的定义看法 百度百科的定义&#xff1a; 商业智能&#xff08;Business Intelligence&#xff0c;简称&#xff1a;BI&#xff09;&#xff0c;又称商业智慧或商务智能&#xff0c;指用现代数据仓库技术、线上分析处理技术、数据挖掘和数据展现技术…...

创建定时任务

import schedule import timedef task():print("Im working...")if __name__ __main__:schedule.every(10).seconds.do(task) # 每10秒一次schedule.every(10).minutes.do(task) # 10分钟一次schedule.every().hour.do(task) # 每小时schedule.every().day.at(&q…...

MyBatis的使用、Spring AOP、Spring事务

一、MyBatis 的使用 1、环境配置 1.1、建库建表 -- 创建数据库 drop database if exists mycnblog; create database mycnblog DEFAULT CHARACTER SET utf8mb4;-- 使⽤数据数据 use mycnblog;-- 创建表[⽤户表] drop table if exists userinfo; create table userinfo(id in…...

AI-调查研究-01-正念冥想有用吗?对健康的影响及科学指南

点一下关注吧&#xff01;&#xff01;&#xff01;非常感谢&#xff01;&#xff01;持续更新&#xff01;&#xff01;&#xff01; &#x1f680; AI篇持续更新中&#xff01;&#xff08;长期更新&#xff09; 目前2025年06月05日更新到&#xff1a; AI炼丹日志-28 - Aud…...

Appium+python自动化(十六)- ADB命令

简介 Android 调试桥(adb)是多种用途的工具&#xff0c;该工具可以帮助你你管理设备或模拟器 的状态。 adb ( Android Debug Bridge)是一个通用命令行工具&#xff0c;其允许您与模拟器实例或连接的 Android 设备进行通信。它可为各种设备操作提供便利&#xff0c;如安装和调试…...

【Linux】C语言执行shell指令

在C语言中执行Shell指令 在C语言中&#xff0c;有几种方法可以执行Shell指令&#xff1a; 1. 使用system()函数 这是最简单的方法&#xff0c;包含在stdlib.h头文件中&#xff1a; #include <stdlib.h>int main() {system("ls -l"); // 执行ls -l命令retu…...

【SpringBoot】100、SpringBoot中使用自定义注解+AOP实现参数自动解密

在实际项目中,用户注册、登录、修改密码等操作,都涉及到参数传输安全问题。所以我们需要在前端对账户、密码等敏感信息加密传输,在后端接收到数据后能自动解密。 1、引入依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId...

微信小程序 - 手机震动

一、界面 <button type"primary" bindtap"shortVibrate">短震动</button> <button type"primary" bindtap"longVibrate">长震动</button> 二、js逻辑代码 注&#xff1a;文档 https://developers.weixin.qq…...

CocosCreator 之 JavaScript/TypeScript和Java的相互交互

引擎版本&#xff1a; 3.8.1 语言&#xff1a; JavaScript/TypeScript、C、Java 环境&#xff1a;Window 参考&#xff1a;Java原生反射机制 您好&#xff0c;我是鹤九日&#xff01; 回顾 在上篇文章中&#xff1a;CocosCreator Android项目接入UnityAds 广告SDK。 我们简单讲…...

【Web 进阶篇】优雅的接口设计:统一响应、全局异常处理与参数校验

系列回顾&#xff1a; 在上一篇中&#xff0c;我们成功地为应用集成了数据库&#xff0c;并使用 Spring Data JPA 实现了基本的 CRUD API。我们的应用现在能“记忆”数据了&#xff01;但是&#xff0c;如果你仔细审视那些 API&#xff0c;会发现它们还很“粗糙”&#xff1a;有…...

vue3+vite项目中使用.env文件环境变量方法

vue3vite项目中使用.env文件环境变量方法 .env文件作用命名规则常用的配置项示例使用方法注意事项在vite.config.js文件中读取环境变量方法 .env文件作用 .env 文件用于定义环境变量&#xff0c;这些变量可以在项目中通过 import.meta.env 进行访问。Vite 会自动加载这些环境变…...

全面解析各类VPN技术:GRE、IPsec、L2TP、SSL与MPLS VPN对比

目录 引言 VPN技术概述 GRE VPN 3.1 GRE封装结构 3.2 GRE的应用场景 GRE over IPsec 4.1 GRE over IPsec封装结构 4.2 为什么使用GRE over IPsec&#xff1f; IPsec VPN 5.1 IPsec传输模式&#xff08;Transport Mode&#xff09; 5.2 IPsec隧道模式&#xff08;Tunne…...

AI书签管理工具开发全记录(十九):嵌入资源处理

1.前言 &#x1f4dd; 在上一篇文章中&#xff0c;我们完成了书签的导入导出功能。本篇文章我们研究如何处理嵌入资源&#xff0c;方便后续将资源打包到一个可执行文件中。 2.embed介绍 &#x1f3af; Go 1.16 引入了革命性的 embed 包&#xff0c;彻底改变了静态资源管理的…...