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

springboot整合mybatis以及mybatis-plus 开发

一、springboot整合mybatis

1.注解版
1.1 导入坐标
<dependencies><!--mybatis坐标--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.2</version></dependency><!--mysql--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.29</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>
1.2 编写配置文件application.yml

#数据源
spring:datasource:username: rootpassword: 123456url:  jdbc:mysql://localhost:3307/testdb?serverTimezone=GMTdriver-class-name: com.mysql.cj.jdbc.Driver
1.3 准备实体类Account ,省略了有参无参 setter getter toString方法
public class Account {private int aid;private String aname;private int amoney;
}
1.4 编写mapper映射器接口

@Mapper//注册注入一个mapper

@MapperScan(basePackages ="com.ztt.mybatis_springboot.mapper")//注册注入多个mapper(以包为单位) )

注意:两者只能写一个

//@Mapper//注册注入一个mapper
public interface AccountMapper {@Select("select * from account")public List<Account> findAll();
}
1.5 编写测试类
@SpringBootTest
class MybatisSpringbootApplicationTests {@Autowired(required = false)AccountMapper accountMapper;@Testvoid contextLoads() {List<Account> all=accountMapper.findAll();for (int i = 0; i <all.size() ; i++) {Account account=all.get(i);System.out.println(account);}}}
1.6 输出结果

2.xml版
2.1 在接口中定义一个方法
public List<Account> find();
2.2 编写xml文件,在resources目录下新建一个mapper包,在mapper包里面新建一个AccountMapper.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.ztt.mybatis_springboot.mapper.AccountMapper"><select id="find" resultType="com.ztt.mybatis_springboot.pojo.Account">select * from account;</select>
</mapper>
2.3 在主配置文件中添加mybatis的配置
mybatis:mapper-locations: mappers/*.xml
2.4 编写测试类
@Testvoid contextLoads1() {List<Account> all=accountMapper.find();for (int i = 0; i <all.size() ; i++) {Account account=all.get(i);System.out.println(account);}}
2.5 输出结果

二、MyBatis-Plus

1.MyBatis-Plus介绍

        MyBatis最佳搭档,只做增强不做改变,为简化开发、提高效率而生。

        详细信息请看官方文档MyBatis-Plus 🚀 为简化开发而生

2.MyBatis-Plus使用步骤:
2.1.坐标
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>

注意:mp坐标添加后,mybatis坐标移除

2.2 编写注解配置实体类与关系表映射关系(truncate清空表以及主键)

@TableName(value = "关联表名称")=========================》修饰在类

@TableField(value = "关联字段名称")======================》修饰在属性

exist = "忽略字段"

@TableId(type="指定主键生成策略,默认雪花算法")=============》修饰在属性

AUTO(0),

NONE(1),

INPUT(2),

ASSIGN_ID(3),

ASSIGN_UUID(4);

@TableName("account")
public class Account {@TableId(value = "aid",type = IdType.AUTO)private int aid;@TableField("aname")private String aname;@TableField("amoney")private int amoney;
}
2.3 使用

BaseMapper===========》公共的数据访问层

IService/ServiceImp==》公共的业务层

//@Mapper//注册注入一个mapper
public interface AccountMapper extends BaseMapper<Account> {@Select("select * from account")public List<Account> findAll();public List<Account> find();
}
2.4 配置yml文件
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
2.5 测试代码使用
2.5.1 新增insert()
@SpringBootTest
public class Test01 {@Autowired(required = false)AccountMapper mapper;//新增@Testpublic void show1(){Account account = new Account("小兔兔", 2000);int row = mapper.insert(account);System.out.println("主键回填id:"+account.getAid());System.out.println("影响行数:"+row);}
}

输出结果:

查看数据库表,发现小兔兔添加成功

2.5.2 修改IDupdateById()
//修改ID@Testpublic void test02()throws Exception{Account account = new Account(3,"小小兔",3000);int row =  mapper.updateById(account);System.out.println("影响行数:"+row);}

输出结果:

查看数据库表表中的小兔兔被改为小小兔,工资改为3000

2.5.3 查询ID selectById()
 //查询ID@Testpublic void test04()throws Exception{Account account = mapper.selectById(3);System.out.println(account);}

输出结果:

2.5.4 查询IDS selectBatchIds(Arrays.asList(5,1,3))
//查询IDS@Testpublic void test05()throws Exception{List<Account> list = mapper.selectBatchIds(Arrays.asList(5,1,3));for (int i = 0; i < list.size(); i++) {Account account =  list.get(i);System.out.println(account);}}

输出结果:

2.5.5 查询count selectCount(null)
//查询count@Testpublic void test06()throws Exception{int count = mapper.selectCount(null);System.out.println(count);}

输出结果:

2.5.6 查询list selectList(queryWrapper)
//查询list@Testpublic void test07()throws Exception{QueryWrapper<Account> queryWrapper = new QueryWrapper();
//        queryWrapper.eq("ahobby","吃饭饭");
//        queryWrapper.eq("aage","18");queryWrapper.eq("ahobby","吃饭饭").or().eq("aage","18");List<Account> list = mapper.selectList(queryWrapper);for (int i = 0; i < list.size(); i++) {Account account =  list.get(i);System.out.println(account);}}

输出结果:

2.5.7 分页

mp分页使用:

注意

1.page.setCurrent(2);当前页码从1开始

2.分页需要配置插件

@Testpublic void test08()throws Exception{//1.定义分页规则Page<Account> page = new Page<Account>();page.setSize(3);//每页记录数page.setCurrent(2);//当前页码//2.查询条件(可选)QueryWrapper queryWrapper = new QueryWrapper();IPage<Account> iPage = mapper.selectPage(page,null);List<Account> list = iPage.getRecords();//分页结果System.out.println("总记录数:"+iPage.getTotal());System.out.println("总记页数:"+iPage.getPages());for (int i = 0; i < list.size(); i++) {Account account =  list.get(i);System.out.println(account);}}

输出结果:

2.5.8 按照ID删除
//查询delete@Testpublic void test09()throws Exception{mapper.deleteById(4);}

输出结果:

LambdaQueryWrapper
1.按照条件查询
@SpringBootTest
public class Test02 {@Autowired(required = false)AccountMapper mapper;@Testpublic void show1(){//1.查询条件LambdaQueryWrapper<Account> lambdaQueryWrapper=new LambdaQueryWrapper<Account>();lambdaQueryWrapper.gt(Account::getAage,18);//2.查询List<Account> list=mapper.selectList(lambdaQueryWrapper);for (int i = 0; i <list.size() ; i++) {Account account=list.get(i);System.out.println(account);}}

输出结果:

2.模拟动态查询1
 //模拟动态查询1@Testpublic void show2(){//1.前端发送来的数据Integer num1 = null;Integer num2 = 30;//1.查询条件LambdaQueryWrapper<Account> lambdaQueryWrapper =  new LambdaQueryWrapper<Account>();//2.判断if(null != num2){lambdaQueryWrapper.lt(Account::getAage,num2);}if(null != num1){lambdaQueryWrapper.gt(Account::getAage,num1);}//3.查询List<Account> list =  mapper.selectList(lambdaQueryWrapper);for (int i = 0; i < list.size(); i++) {Account account =  list.get(i);System.out.println(account);}}

输出结果:

3.模拟动态查询2
//模拟动态查询2@Testpublic void show3(){//1.前端发送来的数据Integer num1 = null;Integer num2 = 30;//1.查询条件LambdaQueryWrapper<Account> lambdaQueryWrapper =  new LambdaQueryWrapper<Account>();//2.判断lambdaQueryWrapper.lt(null != num2,Account::getAage,num2);lambdaQueryWrapper.gt(null != num1,Account::getAage,num1);//3.查询List<Account> list =  mapper.selectList(null);for (int i = 0; i < list.size(); i++) {Account account =  list.get(i);System.out.println(account);}}

输出结果:

4.投影查询-字段查询
//投影查询-字段查询@Testpublic void show4() {//1.条件LambdaQueryWrapper<Account> lambdaQueryWrapper  = new LambdaQueryWrapper<Account>();lambdaQueryWrapper.select(Account::getAname,Account::getAhobby);//2.查询List<Account> list =  mapper.selectList(lambdaQueryWrapper);//4.遍历for (int i = 0; i < list.size(); i++) {Account account =  list.get(i);System.out.println(account);}}

输出结果:

物理删除:业务数据从数据库中丢弃,执行的是delete操作
逻辑删除:为数据设置是否可用状态字段,删除时设置状态字段为不可用状态,数据保留在数据库中,执行的是update操作
        实现步骤:
        步骤1:修改数据库表添加deleted列,比如0代表正常,1代表删除,可以在添加列的同时设置其默认值为0正常。
        步骤2:实体类添加属性以及注解
                @TableLogic(value="0",delval="1")
                private Integer deleted;
                        value为正常数据的值,delval为删除数据的值

5.逻辑删除:
@TableLogic(value = "0",delval = "1")
@TableField("isdelete")
private int isdelete;
@Test
public void show5() {mapper.deleteById(7);
}

输出结果:

查看数据库表中的数据,我们会发现id为7的小熊并没有没删除只是将表中的isdelete改为了1,再次查询表中的数据会发现小熊会被自动屏蔽掉,不会在控制台输出。

相关文章:

springboot整合mybatis以及mybatis-plus 开发

一、springboot整合mybatis 1.注解版 1.1 导入坐标 <dependencies><!--mybatis坐标--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.2</…...

大语言模型微调框架Unsloth:简化模型微调流程,提升模型性能

Unsloth 将 Llama-3、Mistral、Phi-3 和 Gemma 等大型语言模型的微调速度提高了 2 倍&#xff0c;内存使用量减少了 70%&#xff0c;而且准确性不会降低&#xff01; 特点 通过手动派生所有计算繁重的数学步骤和手写 GPU 内核&#xff0c;unsloth 可以在不更改任何硬件的情况…...

IPD-华为研发之道分析与理解

关于西方众多优秀的管理模式、理论我们学习过&#xff0c;也借鉴以及实践过&#xff0c;拿到《IPD-华为研发之道》通读研习后&#xff0c;正如书中所述&#xff0c;IPD是一套产品开发的模式、理念与方法&#xff0c;IPD思想&#xff0c;流程和方法是诸多成功企业优秀实践的经验…...

时空序列顶会文章

ICLR 2024 时间序列&#xff08;Time Series&#xff09;高分论文 - 知乎 (zhihu.com) ICML2024全部论文 icml.cc/virtual/2024/papers.html...

C语言-使用指针数组作为函数参数,实现对10个字符串进行排序

使用指针数组作为函数参数&#xff0c;实现对10个字符串进行排序 1.输入 lisi hahaha hehehe helloa leihoua lisi nihaoa wangwu ajax bureau2.输出 ajax bureau hahaha hehehe helloa leihoua lisi lisi nihaoa wangwu3.程序&#xff1a; #define _CRT_SECURE_NO_WARNING…...

???ABC366:F - Maximum Composition(dp,无序:贪心排序)

问题陈述 给你 NN 个线性函数 f1,f2,…,fNf1​,f2​,…,fN​ &#xff0c;其中 fi(x)AixBifi​(x)Ai​xBi​ . 求由 KK 组成的序列 p(p1,p2,…,pK)p(p1​,p2​,…,pK​) 中 fp1(fp2(…fpK(1)…))fp1​​(fp2​​(…fpK​​(1)…)) 的最大可能值。介于 11 和 NN (含)之间的个不…...

unity项目打包为webgl后应用于vue项目中(iframe模式)的数据交互

参考文章&#xff1a; 1.Unity打包WebGL: 导入Vue 2.unity文档-WebGL&#xff1a;与浏览器脚本交互 3.unity与vue交互(无第三方插件&#xff09; 目录 一、前期工作1.新建.jslib文件2.新建.cs脚本3. 新建一个Text对象和button按钮对象4.添加脚本空对象UIEvent5.导出unity为w…...

【数据结构与算法 | 图篇】Bellman-Ford算法(单源最短路径算法)

1. 前言 前文的迪杰斯特拉算法不能求解有负边的图的最短路径的问题。而此文的Bellman-Ford可以处理含负权边的图算法&#xff0c;并且能检测出图中是否存在负环&#xff08;权重和为负数的环&#xff09;. 2. 基本思想 1. 初始化&#xff1a; 对于所有顶点 v ∈ V \ {s}&am…...

Python | Leetcode Python题解之第336题回文对

题目&#xff1a; 题解&#xff1a; class Solution:def palindromePairs1(self, words: List[str]) -> List[List[int]]:# 核心思想--枚举前缀和后缀# 如果两个字符串k1&#xff0c;k2组成一个回文字符串会出现三种情况# len(k1) len(k2),则需要比较k1 k2[::-1]# len(k1…...

C语言家教记录(六)

导语 本次授课的内容如下&#xff1a;指针&#xff0c;指针和数组 辅助教材为 《C语言程序设计现代方法&#xff08;第2版&#xff09;》 指针 指针变量 计算机按字节划分地址&#xff0c;每个地址访问一个字节 指针变量指向变量的地址&#xff0c;指的是变量第一个字节的…...

C++竞赛初阶L1-11-第五单元-for循环(25~26课)519: T454430 人口增长问题

题目内容 假设目前的世界人口有 x 亿&#xff0c;按照每年 0.1% 的增长速度&#xff0c;n 年后将有多少人&#xff1f; 输入格式 一行两个正整数 x 和 n&#xff0c;之间有一个空格。其中&#xff0c;1≤x≤100,1≤n≤100。 输出格式 一行一个数&#xff0c;表示答案。以亿…...

demo测试

目录 接口commonCodeGenerator entityuser mapperUserMapper controllerUserController serviceUserServiceimplUserServiceImpl mapper.xmlpom.xmlapplication.yml 接口 common CodeGenerator package com.llz.demo.common;import com.baomidou.mybatisplus.core.exceptions…...

TinTinLand Web3 + DePIN 共学月|深入探索 DePIN 项目,全景分析去中心化网络未来

「TinTinLand Web3 主题共学月」是由 TinTinLand 每月发起的主题学习活动&#xff0c;携手知名项目共同打造一个系统化、互动性强的学习平台&#xff0c;帮助开发者不断提升技能&#xff0c;紧跟 Web3 技术的前沿发展。活动通过演示视频、学习打卡、模拟环境、实际操作等多种方…...

Java并发编程(六)

1、java 中有几种方法可以实现一个线程 继承 Thread 类实现 Runnable 接口实现 Callable 接口&#xff0c;需要实现的是 call() 方法 2、如何停止一个正在运行的线程 使用共享变量的方式 在这种方式中&#xff0c;之所以引入共享变量&#xff0c;是因为该变量可以被多个执行…...

k8s对外服务之Ingress

目录 1.Ingress 简介 2.Ingress 组成 3.Ingress-Nginx 工作原理 4.部署 nginx-ingress-controller 5.总结 1.Ingress 简介 service的作用体现在两个方面&#xff0c;对集群内部&#xff0c;它不断跟踪pod的变化&#xff0c;更新endpoint中对应pod的对象&#xff0c;提供了…...

使用Python+moviepy在视频画面上绘制边框

一、 使用VideoFileClip对象的的fx函数设置vfx.margin&#xff0c;在视频画面上绘制边框 from moviepy.editor import * mvVideoFileClip(/home/Download/leaves.mp4) mv2mv.fx(vfx.margin,mar3,color(0,0,255),opacity0.5) # 绘制边框# mar3 &#xff1a;边框宽度3像素&#…...

灵办AI探索之旅:颠覆传统的代码开发工具

前言 灵办AI是一个先进的人工智能工具&#xff0c;专注于提高软件开发和项目管理的效率。其核心功能包括代码生成、优化、评估和自动化修复&#xff0c;旨在帮助开发者和团队提升开发速度和代码质量。 体验地址&#xff1a;https://ilingban.com/browser_extension/?fromjj …...

【Redis】Redis 数据类型与结构—(二)

Redis 数据类型与结构 一、值的数据类型二、键值对数据结构三、集合数据操作效率 一、值的数据类型 Redis “快”取决于两方面&#xff0c;一方面&#xff0c;它是内存数据库&#xff0c;另一方面&#xff0c;则是高效的数据结构。 Redis 键值对中值的数据类型&#xff0c;也…...

Tomcat初篇

目录 Tomcat主要特点Tomcat的核心组件Tomcat使用安装Tomcat配置Tomcat启动和停止Tomcat Tomcat工作原理目录结构配置文件性能优化策略 Tomcat Apache Tomcat是一个开源的Servlet容器和Web服务器&#xff0c;广泛用于运行基于Java的Web应用程序。它实现了Java Servlet和JavaSer…...

机器学习(2)-- KNN算法之手写数字识别

KNN算法 KNN&#xff08;K-Nearest Neighbor&#xff0c;K最近邻&#xff09;算法是一种用于分类和回归的非参数统计方法&#xff0c;尤其在分类问题中表现出色。在手写数字识别领域&#xff0c;KNN算法通过比较测试样本与训练样本之间的距离&#xff0c;找到最近的K个邻居&am…...

RWKV7-1.5B-g1a参数详解教程:max_new_tokens/temperature/top_p调优实操手册

RWKV7-1.5B-g1a参数详解教程&#xff1a;max_new_tokens/temperature/top_p调优实操手册 1. 模型简介 rwkv7-1.5B-g1a 是基于新一代 RWKV-7 架构的多语言文本生成模型&#xff0c;特别适合中文场景下的基础问答、文案创作和简短总结任务。作为轻量级模型&#xff0c;它在保持良…...

雀魂AI助手Akagi:5分钟搭建你的专属麻将教练

雀魂AI助手Akagi&#xff1a;5分钟搭建你的专属麻将教练 【免费下载链接】Akagi A helper client for Majsoul 项目地址: https://gitcode.com/gh_mirrors/ak/Akagi 你是否曾在雀魂游戏中面对复杂牌局不知所措&#xff1f;是否想提升麻将技巧却苦于没有专业指导&#xf…...

从0到1:Java+AI入门实战,看完直接上手项目

文章目录前言环境准备&#xff1a;别急着装Python&#xff0c;先把JDK升到21第一滴血&#xff1a;让Java程序说出"人话"进阶玩法&#xff1a;给AI装上"记忆"和"工具"让AI记住你们聊过啥让AI能查数据库、调接口实战项目&#xff1a;搭建私有知识库…...

luci-app-unblockneteasemusic 插件完整技术指南:实现网易云音乐播放限制解除

luci-app-unblockneteasemusic 插件完整技术指南&#xff1a;实现网易云音乐播放限制解除 【免费下载链接】luci-app-unblockneteasemusic [OpenWrt] 解除网易云音乐播放限制 项目地址: https://gitcode.com/gh_mirrors/lu/luci-app-unblockneteasemusic luci-app-unblo…...

OpenClaw版本升级:nanobot镜像迁移全记录

OpenClaw版本升级&#xff1a;nanobot镜像迁移全记录 1. 升级背景与准备工作 去年我在本地部署了基于OpenClaw v1.2的nanobot镜像&#xff0c;这套系统一直稳定运行着我的自动化办公流程。直到上个月收到社区通知&#xff0c;新版本v2.1重构了核心架构&#xff0c;特别是技能…...

Keepalived+Nginx+Tomcat 高可用项目集成 MySQL 数据库全记录

前言在之前的文章中&#xff0c;我搭建了基于 KeepalivedNginxTomcat 的高可用 Web 架构&#xff0c;实现了入口 VIP 漂移和反向代理。但这套架构还缺少“数据层”——所有服务都是无状态的&#xff0c;不能持久化数据。为了让项目更完整&#xff0c;我决定加入 MySQL 数据库&a…...

轻量级工具G-Helper:一站式解决ROG游戏本色彩配置异常问题

轻量级工具G-Helper&#xff1a;一站式解决ROG游戏本色彩配置异常问题 【免费下载链接】g-helper Lightweight Armoury Crate alternative for Asus laptops. Control tool for ROG Zephyrus G14, G15, G16, M16, Flow X13, Flow X16, TUF, Strix, Scar and other models 项目…...

AdaptixC2实战(一)Hack Smart Security

前言: 本篇是AdaptixC2实战系列的第一篇,环境是 THM 上的 Hack Smart Security 靶机。我们将学习和使用AdaptixC2进行操作,基于AdaptixC2工具所提供的能力,探讨AdaptixC2的使用技巧及操作安全。 背景(纯虚构): 你的任务是渗透臭名昭著的 Hack Smarter APT 组织的服务器…...

AI原生应用的微服务架构设计模式

AI原生应用的微服务架构设计模式&#xff1a;用智能餐厅的故事讲透AI与微服务的碰撞关键词&#xff1a;AI原生应用、微服务架构、设计模式、模型生命周期、实时数据流摘要&#xff1a;当AI大模型、边缘计算和实时决策需求爆发时&#xff0c;传统单体架构已无法满足AI应用的动态…...

UniApp实战:如何安全高效地在安卓10+设备上实现本地数据存储(附权限配置避坑指南)

UniApp安卓10本地数据存储实战&#xff1a;权限配置与高性能方案设计 当你的UniApp在安卓10设备上突然无法保存用户配置时&#xff0c;控制台那行冰冷的"Permission denied"可能让整个开发团队陷入深夜加班。这不是简单的API调用问题&#xff0c;而是安卓存储机制变革…...