SpringBoot整合Mybatis-Plus实践汇总

相关依赖

  MyBatis-Plus涉及的依赖主要是Mybatis-start、和分页插件的依赖,不考虑使用额外分页插件的前提下,只需要mybatis-plus-boot-starter一个依赖即可与SpringBoot集成:

<!--Mybatis-plugs--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.2</version></dependency>

SpringBoot基本引入Mybatis-Plus用法

Mybatis-plus的配置详解

SpringBoot引入Mybatis-Plus遵循start原则,配置化继承自Mybatis,关于数据库配置保持一致即可

spring:#数据库连接配置datasource:url: jdbc:mysql://localhost:3306/db_blog?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghaiusername: rootpassword: 1234driver-class-name: com.mysql.cj.jdbc.Driver

以下是Mybatis-Plus独有的配置

# MyBatis-Plus 配置
mybatis-plus:# MyBatis-Plus 的全局配置global-config:#banner图是否在日志中输出banner: off# 数据库相关配置db-config:# 主键类型id-type: auto  # 可选值:auto, assign_id, assign_uuid, input# MyBatis-Plus 的配置configuration:# 是否开启驼峰命名转换map-underscore-to-camel-case: true# 日志实现log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  # 控制台输出 SQL 日志# 类路径下的 Mapper XML 文件位置mapper-locations: classpath*:mapper/*.xml# 类型别名包type-aliases-package: com.example.myapp.entity  # 实体类所在的包(默认不需要额外配置)

 如无特殊要求情况下,只需要简化配置即可, 其他配置项会自动不使用或者使用缺省值,以下为一个简化配置样例:

mybatis-plus:global-config:banner: offmapper-locations: classpath*:mapper/*.xml#configuration:#log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  调试环境下打开,开启sql日志打印

基本代码结构

实体类

实体类定义,实体类主要与表或者业务概念对应,一般与表对应时,可配合使用相关的@Table家族注解:

@Data
//指定数据库中的表
@TableName("tb_artitle_data")
public class ArticleEntity implements Serializable {@TableIdprivate Int id;private String artName;private String artDesc;private String artUrl;private String artTime;//表中无此字段,Mapper处理时可略过此字段@TableField(exist = false)private String auth;
}

创建Mapper,相比于Mybatis的Mapper需要与XML关联,Mybatis-Plus的优势在于,对于基础的增删改查,可以不需要额外创建XML,如下:

@Mapper
//只需要Mapper注解,然后继承BaseMapper即可,泛型指定为对应表的实体类
public interface ArticleMapper extends BaseMapper<ArticleEntity> {
}

 简单使用,直接在Service代码中引入Mapper,使用BaseMapper中已经定义好的方法,结合QueryWrapper方法,省略SQL

@Service
public class ArticleServiceImpl implements ArticleService {@Autowiredprivate ArticleMapper articleMapper;// 新增文章@Overridepublic boolean addArticle(ArticleEntity article) {return articleMapper.insert(article) > 0;}// 删除文章@Overridepublic boolean deleteArticle(String id) {return articleMapper.deleteById(id) > 0;}// 更新文章@Overridepublic boolean updateArticle(ArticleEntity article) {return articleMapper.updateById(article) > 0;}// 根据ID查询文章@Overridepublic ArticleEntity getArticleById(String id) {return articleMapper.selectById(id);}// 查询所有文章@Overridepublic List<ArticleEntity> getAllArticles() {return articleMapper.selectList(null);}// 分页查询文章@Overridepublic IPage<ArticleEntity> getArticlesByPage(int currentPage, int pageSize) {Page<ArticleEntity> page = new Page<>(currentPage, pageSize);return articleMapper.selectPage(page, null);}// 多条件组合查询文章public List<ArticleEntity> getArticlesByMultipleConditions(String artName, String artDesc, String artUrl, String startTime, String endTime) {QueryWrapper<ArticleEntity> queryWrapper = new QueryWrapper<>();if (artName != null && !artName.isEmpty()) {queryWrapper.eq("art_name", artName);}if (artDesc != null && !artDesc.isEmpty()) {queryWrapper.like("art_desc", artDesc);}if (artUrl != null && !artUrl.isEmpty()) {queryWrapper.eq("art_url", artUrl);}if (startTime != null && !startTime.isEmpty() && endTime != null && !endTime.isEmpty()) {queryWrapper.between("art_time", startTime, endTime);}return articleMapper.selectList(queryWrapper);}
}

还可以基于Mybatis-Plus自带的IService风格进行开发:

public interface ArticleService extends IService<ArticleEntity> {// 多条件查询文章List<ArticleEntity> getArticlesByMultipleConditions(String artName, String artDesc, String artUrl, String startTime, String endTime);
}@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, ArticleEntity> implements ArticleService {// 新增文章@Overridepublic boolean save(ArticleEntity entity) {return super.save(entity);}// 删除文章@Overridepublic boolean removeById(String id) {return super.removeById(id);}// 更新文章@Overridepublic boolean updateById(ArticleEntity entity) {return super.updateById(entity);}// 根据ID查询文章@Overridepublic ArticleEntity getById(String id) {return super.getById(id);}// 查询所有文章public List<ArticleEntity> listAll() {return super.list();}// 分页查询文章public IPage<ArticleEntity> pageList(Page<ArticleEntity> page) {return super.page(page);}// 多条件查询文章@Overridepublic List<ArticleEntity> getArticlesByMultipleConditions(String artName, String artDesc, String artUrl, String startTime, String endTime) {QueryWrapper<ArticleEntity> queryWrapper = new QueryWrapper<>();// 动态添加查询条件if (artName != null && !artName.isEmpty()) {queryWrapper.eq("art_name", artName);}if (artDesc != null && !artDesc.isEmpty()) {queryWrapper.like("art_desc", artDesc);}if (artUrl != null && !artUrl.isEmpty()) {queryWrapper.eq("art_url", artUrl);}if (startTime != null && !startTime.isEmpty() && endTime != null && !endTime.isEmpty()) {queryWrapper.between("art_time", startTime, endTime);}return list(queryWrapper);}
}

Mapper层加强

基于注解编写复杂SQL

MyBatis-Plus 提供了注解方式可以在 Mapper 层编写复杂的 SQL 语句。这种方式省略掉了繁重的XML文件

@Mapper
public interface ArticleMapper extends BaseMapper<ArticleEntity> {// 根据多个条件查询文章@Select({"<script>","SELECT * FROM tb_article_data","WHERE 1=1","<if test='artName != null and !artName.isEmpty()'> AND art_name = #{artName} </if>","<if test='artDesc != null and !artDesc.isEmpty()'> AND art_desc LIKE CONCAT('%', #{artDesc}, '%') </if>","<if test='artUrl != null and !artUrl.isEmpty()'> AND art_url = #{artUrl} </if>","<if test='startTime != null and !startTime.isEmpty() and endTime != null and !endTime.isEmpty()'> AND art_time BETWEEN #{startTime} AND #{endTime} </if>","</script>"})List<ArticleEntity> selectByMultipleConditions(@Param("artName") String artName,@Param("artDesc") String artDesc,@Param("artUrl") String artUrl,@Param("startTime") String startTime,@Param("endTime") String endTime);// 插入文章并返回自动生成的ID@Insert({"INSERT INTO tb_article_data (art_name, art_desc, art_url, art_time)","VALUES (#{artName}, #{artDesc}, #{artUrl}, #{artTime})","RETURNING id"})@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")int insertAndReturnId(@Param("article") ArticleEntity article);// 更新文章信息@Update({"<script>","UPDATE tb_article_data","SET art_name = #{artName}, art_desc = #{artDesc}, art_url = #{artUrl}, art_time = #{artTime}","WHERE id = #{id}","</script>"})int updateArticle(@Param("article") ArticleEntity article);// 删除文章@Delete("DELETE FROM tb_article_data WHERE id = #{id}")int deleteArticleById(@Param("id") String id);// 使用存储过程@Select("CALL GetArticleById(#{id})")@Results({@Result(property = "id", column = "id", jdbcType = JdbcType.VARCHAR),@Result(property = "artName", column = "art_name", jdbcType = JdbcType.VARCHAR),@Result(property = "artDesc", column = "art_desc", jdbcType = JdbcType.VARCHAR),@Result(property = "artUrl", column = "art_url", jdbcType = JdbcType.VARCHAR),@Result(property = "artTime", column = "art_time", jdbcType = JdbcType.VARCHAR)})ArticleEntity callGetArticleById(@Param("id") String id);// 使用XML中的SQL片段@Select("${sqlFragment}")List<ArticleEntity> selectBySqlFragment(@Param("sqlFragment") String sqlFragment);//查询文章数量@Select("SELECT COUNT(*) FROM tb_article_data")int countAllArticles();
}

基于XML编写复杂SQL

也可以沿用Mybatis的方式,使用XML进行复杂SQL的编写

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.example.mapper.ArticleMapper"><!-- 根据多个条件查询文章 --><select id="selectByMultipleConditions" resultType="com.example.entity.ArticleEntity">SELECT * FROM tb_article_data<where><if test="artName != null and artName != ''">AND art_name = #{artName}</if><if test="artDesc != null and artDesc != ''">AND art_desc LIKE CONCAT('%', #{artDesc}, '%')</if><if test="artUrl != null and artUrl != ''">AND art_url = #{artUrl}</if><if test="startTime != null and startTime != '' and endTime != null and endTime != ''">AND art_time BETWEEN #{startTime} AND #{endTime}</if></where></select><!-- 插入文章并返回自动生成的ID --><insert id="insertAndReturnId" useGeneratedKeys="true" keyProperty="id">INSERT INTO tb_article_data (art_name, art_desc, art_url, art_time)VALUES (#{artName}, #{artDesc}, #{artUrl}, #{artTime})</insert><!-- 更新文章信息 --><update id="updateArticle">UPDATE tb_article_dataSETart_name = #{artName},art_desc = #{artDesc},art_url = #{artUrl},art_time = #{artTime}WHERE id = #{id}</update><!-- 删除文章 --><delete id="deleteArticleById">DELETE FROM tb_article_data WHERE id = #{id}</delete><!-- 使用存储过程 --><select id="callGetArticleById" resultType="com.example.entity.ArticleEntity">CALL GetArticleById(#{id})</select><!-- 查询文章数量 --><select id="countAllArticles" resultType="int">SELECT COUNT(*) FROM tb_article_data</select></mapper>

Mybatis-Plus的分页实现

内置的分页拦截器

MyBatis-Plus 提供了内置的分页拦截器,可以通过配置来启用分页功能。

@Configuration
public class MyBatisPlusConfigure {/*** 分页插件,自动识别数据库类型*/@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();// 添加分页插件interceptor.addInnerInterceptor(new PaginationInnerInterceptor());return interceptor;}}

使用IPage进行分页参数设置和结果获取

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, ArticleEntity> implements ArticleService {// 分页查询文章public IPage<ArticleEntity> pageList(int currentPage, int pageSize) {Page<ArticleEntity> page = new Page<>(currentPage, pageSize);return baseMapper.selectPage(page, null);}// 多条件分页查询文章public IPage<ArticleEntity> pageListByMultipleConditions(int currentPage, int pageSize, String artName, String artDesc, String artUrl, String startTime, String endTime) {Page<ArticleEntity> page = new Page<>(currentPage, pageSize);QueryWrapper<ArticleEntity> queryWrapper = new QueryWrapper<>();if (artName != null && !artName.isEmpty()) {queryWrapper.eq("art_name", artName);}if (artDesc != null && !artDesc.isEmpty()) {queryWrapper.like("art_desc", artDesc);}if (artUrl != null && !artUrl.isEmpty()) {queryWrapper.eq("art_url", artUrl);}if (startTime != null && !startTime.isEmpty() && endTime != null && !endTime.isEmpty()) {queryWrapper.between("art_time", startTime, endTime);}return baseMapper.selectPage(page, queryWrapper);}
}

 使用XML的SQL分页,需要将Page作为参数给到Mapper层的方法

public interface ArticleMapper extends BaseMapper<ArticleEntity> {// 查询所有文章List<ArticleEntity> selectAllArticles();// 根据多个条件查询文章List<ArticleEntity> selectByMultipleConditions(@Param("page") Page<AtricleEntity> page,@Param("artName") String artName,@Param("artDesc") String artDesc,@Param("artUrl") String artUrl,@Param("startTime") String startTime,@Param("endTime") String endTime);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.example.mapper.ArticleMapper"><!-- 查询所有文章 --><select id="selectAllArticles" resultType="com.example.entity.ArticleEntity">SELECT * FROM tb_article_data</select><!-- 根据多个条件查询文章 --><select id="selectByMultipleConditions" resultType="com.example.entity.ArticleEntity">SELECT * FROM tb_article_data<where><if test="artName != null and artName != ''">AND art_name = #{artName}</if><if test="artDesc != null and artDesc != ''">AND art_desc LIKE CONCAT('%', #{artDesc}, '%')</if><if test="artUrl != null and artUrl != ''">AND art_url = #{artUrl}</if><if test="startTime != null and startTime != '' and endTime != null and endTime != ''">AND art_time BETWEEN #{startTime} AND #{endTime}</if></where></select></mapper>
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, ArticleEntity> implements ArticleService {// 使用 XML 定义的多条件查询方法进行分页查询public IPage<ArticleEntity> pageListByMultipleConditionsUsingXml(int currentPage, int pageSize, String artName, String artDesc, String artUrl, String startTime, String endTime) {Page<ArticleEntity> page = new Page<>(currentPage, pageSize);Ipage<ArticleEntity> data= baseMapper.selectByMultipleConditions(page ,artName, artDesc, artUrl, startTime, endTime);return data;}
}

使用第三方的分页插件

PageHelper 是一个非常流行的 MyBatis 分页插件,具有易用简便的特点,且与Mybatis-Plus无缝连接。

引入依赖:

    <dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>5.2.0</version></dependency>

在 application.yml 中配置 PageHelper

pagehelper:helperDialect: mysqlreasonable: truesupportMethodsArguments: trueparams: count=countSql

使用PageHelper

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, ArticleEntity> implements ArticleService {// 分页查询文章public PageInfo<ArticleEntity> pageListWithPageHelper(int currentPage, int pageSize) {PageHelper.startPage(currentPage, pageSize);List<ArticleEntity> articles = baseMapper.selectList(null);return new PageInfo<>(articles);}// 多条件分页查询文章public PageInfo<ArticleEntity> pageListByMultipleConditionsWithPageHelper(int currentPage, int pageSize, String artName, String artDesc, String artUrl, String startTime, String endTime) {PageHelper.startPage(currentPage, pageSize);QueryWrapper<ArticleEntity> queryWrapper = new QueryWrapper<>();if (artName != null && !artName.isEmpty()) {queryWrapper.eq("art_name", artName);}if (artDesc != null && !artDesc.isEmpty()) {queryWrapper.like("art_desc", artDesc);}if (artUrl != null && !artUrl.isEmpty()) {queryWrapper.eq("art_url", artUrl);}if (startTime != null && !startTime.isEmpty() && endTime != null && !endTime.isEmpty()) {queryWrapper.between("art_time", startTime, endTime);}List<ArticleEntity> articles = baseMapper.selectList(queryWrapper);return new PageInfo<>(articles);}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/886394.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

SSE与WebSocket与MQTT

SSE <template><div><h1>实时消息</h1><ul><li v-for"(msg, index) in messages" :key"index">{{ msg }}</li></ul></div> </template><script setup> import { ref, onMounted, onUn…

计算机网络各层设备总结归纳(更新ing)

计算机网络按照OSI&#xff08;开放式系统互联&#xff09;模型分为七层&#xff0c;每一层都有其特定的功能和对应的网络设备。以下是各层对应的设备&#xff1a; 1. 物理层&#xff08;Physical Layer) 设备&#xff1a;中继器&#xff08;Repeater&#xff09;、集线器…

Oracle19C AWR报告分析之Wait Classes by Total Wait Time

Oracle19C AWR报告分析之Wait Classes by Total Wait Time 一、分析数据二、详细分析2.1 指标参数介绍2.2 数据库性能分析2.3 综合性能评估 在 Oracle 数据库的 AWR 报告中&#xff0c;Wait Classes by Total Wait Time 是评估数据库性能的重要部分。本篇文章主要是介绍指标参数…

基本数据类型和包装类型的区别、缓存池、自动拆箱装箱(面试题)

目录 1. 八种基本类型及对应包装类型 2. 基本类型和包装类型 区别 3. 自动拆箱装箱 3.1 自动装箱 3.2 自动拆箱 3.3 缓存池 4. 高频面试案例分析 1. 八种基本类型及对应包装类型 基本数据类型类型描述范围&#xff08;指数形式&#xff09;位数包装类型byte整型&#x…

C#中object和dynamic

在C#中&#xff0c;object和dynamic都是用于存储不同类型值的类型&#xff0c;但它们之间存在一些关键的区别&#xff1a; object object是C#中的基元类型之一&#xff0c;是所有其他类型的最终基类。当你将一个值赋给object类型的变量时&#xff0c;编译器会执行装箱操作&am…

Python酷库之旅-第三方库Pandas(221)

目录 一、用法精讲 1036、pandas.DatetimeIndex.to_pydatetime方法 1036-1、语法 1036-2、参数 1036-3、功能 1036-4、返回值 1036-5、说明 1036-6、用法 1036-6-1、数据准备 1036-6-2、代码示例 1036-6-3、结果输出 1037、pandas.DatetimeIndex.to_series方法 10…

基于SpringBoot网上超市的设计与实现录像

基于SpringBoot网上超市的设计与实现录像 SpringBoot网上超市的设计与实现录像

【vmware+ubuntu16.04】vm虚拟机及镜像安装-tools安装包弹不出来问题

学习机器人这门课需要下载虚拟机&#xff0c;做一下记录 首先我下载的是vm虚拟机16&#xff0c; 下载版本可参考该文章课堂上我下载 的镜像是16.04&#xff0c;虚拟机安装教程和镜像添加可参考该博主 按照教程安装成功 安装tools&#xff0c;但是我的弹不出来那个压缩包&…

ssm126基于HTML5的出租车管理系统+jsp(论文+源码)_kaic

设计题目&#xff1a;出租车管理系统的设计与实现 摘 要 网络技术和计算机技术发展至今&#xff0c;已经拥有了深厚的理论基础&#xff0c;并在现实中进行了充分运用&#xff0c;尤其是基于计算机运行的软件更是受到各界的关注。加上现在人们已经步入信息时代&#xff0c;所以…

方法论-WPS模型(高效沟通和决策分析的框架)

WPS模型&#xff08;What, Problem, Solution&#xff09;是一种高效沟通和决策分析的框架&#xff0c;旨在帮助沟通者清晰、简洁地表达问题和解决方案&#xff0c;特别适用于在复杂或多变的环境中进行清晰的交流。WPS模型的核心是通过以下三个步骤来组织沟通内容&#xff1a; …

Qt 项目架构设计

在开发一个 Qt 项目时&#xff0c;合理的文件夹结构和清晰的构建流程是非常重要的。Qt 项目通常需要管理源代码、UI 文件、资源文件、构建脚本等。下面我会给出一个详细的文件夹结构示例&#xff0c;并解释每个部分的作用及如何设计 Makefile 或使用 Qt 的 qmake 来自动化构建过…

游戏引擎学习第14天

视频参考:https://www.bilibili.com/video/BV1iNUeYEEj4/ 1. 为什么关注内存管理&#xff1f; 内存分配是潜在的失败点&#xff1a; 每次进行内存分配&#xff08;malloc、new等&#xff09;时&#xff0c;都可能失败&#xff08;例如内存不足&#xff09;。这种失败会引入不稳…

阿里云引领智算集群网络架构的新一轮变革

阿里云引领智算集群网络架构的新一轮变革 云布道师 11 月 8 日~ 10 日在江苏张家港召开的 CCF ChinaNet&#xff08;即中国网络大会&#xff09;上&#xff0c;众多院士、教授和业界技术领袖齐聚一堂&#xff0c;畅谈网络未来的发展方向&#xff0c;聚焦智算集群网络的创新变…

git/dvc笔记

目录 gitHEAD<commit_id>git checkoutgit reset文件跟踪状态git ls-filesgit rm.gitignoregit diff首次使用git的必要配置 dvcdvc installdvc statusdvc diffdvc config cache.type git HEAD HEAD表示分支的最新提交节点 前一个提交版本&#xff1a;HEAD^ HEAD~1 HEA…

【更新至2023】A股上市公司企业突破性创新、渐进性创新数据(2000-2023年)

测算方式&#xff1a;参考C刊《财经问题研究》胡山&#xff08;2022&#xff09;老师的研究&#xff0c;用当年获得授权的发明专利数量加 1 后取自然对数来衡量企业突破性创新 ( Invention) ; 用非发明专利 ( 包括实用新型专利和外观设计专利) 授权量加 1 后取自然对数来衡量企…

【Android、IOS、Flutter、鸿蒙、ReactNative 】启动页

Android 设置启动页 自定义 splash.xml 通过themes.xml配置启动页背景图 IOS 设置启动页 LaunchScreen.storyboard 设置为启动页 storyboard页面绘制 Assets.xcassets 目录下导入图片 AppLogo Flutter 设置启动页 Flutter Android 设置启动页 自定义 launch_background.xm…

Elasticsearch:管理和排除 Elasticsearch 内存故障

作者&#xff1a;来自 Elastic Stef Nestor 随着 Elastic Cloud 提供可观察性、安全性和搜索等解决方案&#xff0c;我们将使用 Elastic Cloud 的用户范围从完整的运营团队扩大到包括数据工程师、安全团队和顾问。作为 Elastic 支持代表&#xff0c;我很乐意与各种各样的用户和…

Jmeter基础篇(24)Jmeter目录下有哪些文件夹是可以删除,且不影响使用的呢?

一、前言 Jmeter使我们日常做性能测试最常用的工具之一啦&#xff01;但是我们在和其他同学协同工作的时候&#xff0c;偶尔也会遇到一些问题&#xff0c;例如我想要给别人发送一个Jmeter工具包&#xff0c;但这个文件包往往会很大&#xff0c;比较浪费流量和空间&#xff0c;…

排序算法(基础)大全

一、排序算法的作用&#xff1a; 排序算法的主要作用是将一组数据按照特定的顺序进行排列&#xff0c;使得数据更加有序和有组织。 1. 查找效率&#xff1a;通过将数据进行排序&#xff0c;可以提高查找算法的效率。在有序的数据中&#xff0c;可以使用更加高效的查找算法&…

如何在 WordPress 中轻松强制所有用户退出登录

作为一名长期管理 WordPress 网站的站长&#xff0c;我深知维护网站安全性的重要性。尤其是在面对会员网站或付费内容平台时&#xff0c;确保所有用户的登录状态是最新的&#xff0c;是维持网站正常运营的关键之一。今天&#xff0c;我就分享一下如何通过简单的步骤&#xff0c…