MyBatis写法汇总

Mybatis写法汇总

1. 批量操作

1.1 批量插入

<insert id="batchInsert" parameterType="java.util.List">INSERT INTO user (username, password, create_time) VALUES<foreach collection="list" item="item" separator=",">(#{item.username}, #{item.password}, #{item.createTime})</foreach>
</insert>

1.2 批量更新

<update id="batchUpdate" parameterType="java.util.List"><foreach collection="list" item="item" separator=";">UPDATE userSET username = #{item.username}, password= #{item.password}WHERE id = #{item.id}</foreach>
</update>

1.3 批量删除

<delete id="batchDelete" parameterType="java.util.List">DELETE FROM user WHERE id IN<foreach collection="list" item="id" open="(" separator="," close=")">#{id}</foreach>
</delete>

通过使用<foreach> 标签,我们可以将多个操作合并为一条SQL语句,大大减少了数据库交互次数,提高了操作效率。

2. 动态SQL

动态SQL是MyBatis的强大特性之一,允许我们根据不同的条件动态构建SQL语句。<if>标签是实现动态SQL的核心。

2.1 动态查询

<select id="findUsers" resultType="User">SELECT * FROM userWHERE 1=1<if test="username != null and username != ''">AND username LIKE CONCAT('%', #{username}, '%')</if><if test="email != null and email != ''">AND email = #{email}</if><if test="status != null">AND status = #{status}</if>
</select>

3. 多条件分支查询

对于更复杂的查询逻辑,我们可以使用<choose>、<when>和<otherwise>标签来实现多条件分支查询。

<select id="findUsersByCondition" resultType="User">SELECT * FROM userWHERE 1=1<choose><when test="searchType == 'username'">AND username LIKE CONCAT('%', #{keyword}, '%')</when><when test="searchType == 'email'">AND email LIKE CONCAT('%', #{keyword}, '%')</when><otherwise>AND (username LIKE CONCAT('%', #{keyword}, '%') OR email LIKE CONCAT('%', #{keyword}, '%'))</otherwise></choose>
</select>

这个例子展示了如何根据不同的搜索类型选择不同的查询条件,如果没有指定搜索类型,则默认搜索用户名和邮箱。

4. SQL语句优化

使用 <trim> 标签可以帮助我们优化生成的SQL语句,避免出现多余的AND或OR关键字。

<select id="findUsers" resultType="User">SELECT * FROM user<trim prefix="WHERE" prefixOverrides="AND |OR "><if test="username != null and username != ''">AND username LIKE CONCAT('%', #{username}, '%')</if><if test="email != null and email != ''">AND email = #{email}</if><if test="status != null">AND status = #{status}</if></trim>
</select>

在这个例子中,<trim>标签会自动去除第一个多余的AND或OR,并在有查询条件时添加WHERE关键字。

5. 自动生成主键

在插入操作中,我们经常需要获取数据库自动生成的主键。MyBatis提供了<selectKey>标签来实现这一功能。

<insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="id"><selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">SELECT 2531020</selectKey>INSERT INTO user (username, email, create_time)VALUES (#{username}, #{email}, #{createTime})
</insert>

在这个例子中,插入操作完成后,会自动执行SELECT 2531020获取新插入记录的ID,并将其赋值给传入的User对象的id属性。

6. 注解方式使用MyBatis

除了XML配置,MyBatis还支持使用注解来定义SQL操作,这种方式可以使代码更加简洁。

public interface UserMapper {@Select("SELECT * FROM user WHERE id = #{id}")User getUserById(Long id);@Insert("INSERT INTO user (username, email, create_time) VALUES (#{username}, #{email}, #{createTime})")@Options(useGeneratedKeys = true, keyProperty = "id")int insertUser(User user);@Update("UPDATE user SET username = #{username}, email = #{email} WHERE id = #{id}")int updateUser(User user);@Delete("DELETE FROM user WHERE id = #{id}")int deleteUser(Long id);
}

这种方式适合简单的CRUD操作,但对于复杂的SQL语句,仍然建议使用XML配置。

7. 高级映射

MyBatis提供了强大的对象关系映射功能,可以处理复杂的表关系。

一对多映射示例:

<resultMap id="userWithOrdersMap" type="User"><id property="id" column="user_id"/><result property="username" column="username"/><collection property="orders" ofType="Order"><id property="id" column="order_id"/><result property="orderNumber" column="order_number"/><result property="createTime" column="order_create_time"/></collection>
</resultMap><select id="getUserWithOrders" resultMap="userWithOrdersMap">SELECT u.id as user_id, u.username, o.id as order_id, o.order_number, o.create_time as order_create_timeFROM user uLEFT JOIN orders o ON u.id = o.user_idWHERE u.id = #{userId}
</select>

8. MyBatis-Plus集成

MyBatis-Plus是MyBatis的增强工具,它提供了许多便捷的CRUD操作和强大的条件构造器。

MyBatis-Plus使用示例:

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {public List<User> findUsersByCondition(String username, String email) {return this.list(new QueryWrapper<User>().like(StringUtils.isNotBlank(username), "username", username).eq(StringUtils.isNotBlank(email), "email", email));}
}

在这个例子中,我们使用MyBatis-Plus提供的条件构造器来动态构建查询条件,无需编写XML。

9. 事务管理

在Spring环境中,我们可以使用@Transactional注解来管理事务,确保数据的一致性。
事务管理示例:

@Service
public class UserService {@Autowiredprivate UserMapper userMapper;@Transactionalpublic void createUserWithOrders(User user, List<Order> orders) {userMapper.insert(user);for (Order order : orders) {order.setUserId(user.getId());orderMapper.insert(order);}}
}

在这个例子中,创建用户和订单的操作被包装在一个事务中,如果任何一步失败,整个操作都会回滚。

10. 缓存机制

MyBatis提供了一级缓存和二级缓存,可以有效提高查询性能。

二级缓存配置示例:

<cacheeviction="LRU"flushInterval="60000"size="512"readOnly="true"/>

这个配置启用了LRU淘汰策略的二级缓存,缓存容量为512个对象,每60秒刷新一次。

11. 插件使用

MyBatis插件可以拦截核心方法的调用,实现如分页、性能分析等功能。
分页插件示例 (使用PageHelper):

@Service
public class UserService {@Autowiredprivate UserMapper userMapper;public PageInfo<User> getUserList(int pageNum, int pageSize) {PageHelper.startPage(pageNum, pageSize);List<User> users = userMapper.selectAll();return new PageInfo<>(users);}
}

这个例子展示了如何使用PageHelper插件实现简单的分页功能。

12. 多数据源配置

在某些场景下,我们需要在同一个应用中操作多个数据库。MyBatis支持配置多个数据源来实现这一需求。

多数据源配置示例:

@Configuration
public class DataSourceConfig {@Bean@ConfigurationProperties("spring.datasource.primary")public DataSource primaryDataSource() {return DataSourceBuilder.create().build();}@Bean@ConfigurationProperties("spring.datasource.secondary")public DataSource secondaryDataSource() {return DataSourceBuilder.create().build();}@Beanpublic SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();factoryBean.setDataSource(dataSource);return factoryBean.getObject();}@Beanpublic SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();factoryBean.setDataSource(dataSource);return factoryBean.getObject();}
}

这个配置类定义了两个数据源和对应的SqlSessionFactory,可以在不同的Mapper中使用不同的数据源。

13. 读写分离

读写分离是提高数据库性能的常用策略。MyBatis可以通过配置多数据源来实现简单的读写分离。

读写分离配置示例:

@Configuration
public class DataSourceConfig {@Bean@ConfigurationProperties("spring.datasource.master")public DataSource masterDataSource() {return DataSourceBuilder.create().build();}@Bean@ConfigurationProperties("spring.datasource.slave")public DataSource slaveDataSource() {return DataSourceBuilder.create().build();}@Beanpublic DataSource routingDataSource(@Qualifier("masterDataSource") DataSource masterDataSource,@Qualifier("slaveDataSource") DataSource slaveDataSource) {Map<Object, Object> targetDataSources = new HashMap<>();targetDataSources.put(DataSourceType.MASTER, masterDataSource);targetDataSources.put(DataSourceType.SLAVE, slaveDataSource);AbstractRoutingDataSource routingDataSource = new AbstractRoutingDataSource() {@Overrideprotected Object determineCurrentLookupKey() {return DataSourceContextHolder.getDataSourceType();}};routingDataSource.setTargetDataSources(targetDataSources);routingDataSource.setDefaultTargetDataSource(masterDataSource);return routingDataSource;}
}

这个例子定义了一个动态数据源,可以根据上下文选择主库或从库。你需要实现一个DataSourceContextHolder来管理当前线程的数据源类型。

14. SQL分析和优化

MyBatis提供了SQL执行分析功能,可以帮助我们找出性能瓶颈。
SQL分析配置示例:

<plugins><plugin interceptor="com.github.pagehelper.PageInterceptor"><!-- 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 --><property name="offsetAsPageNum" value="true"/><!-- 设置为true时,使用RowBounds分页会进行count查询 --><property name="rowBoundsWithCount" value="true"/></plugin><plugin interceptor="org.apache.ibatis.plugin.Interceptor"><property name="properties">sqlCollector=com.example.SqlCollector</property></plugin>
</plugins>

在这个配置中,我们不仅加入了分页插件,还加入了一个自定义的SQL收集器,可以用于分析SQL执行情况。

总结

我们详细介绍了14种MyBatis的高级用法和技巧,涵盖了从基本的CRUD操作优化到复杂的多数据源配置和读写分离等高级主题。这些技巧可以帮助开发者更高效地使用MyBatis,构建出性能更好、可维护性更强的应用系统。

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

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

相关文章

【C语言程序设计——入门】C语言程序开发环境(头歌实践教学平台习题)【合集】

目录&#x1f60b; <第1关&#xff1a;程序改错> 任务描述 相关知识 编程要求 测试说明 我的通关代码: 测试结果&#xff1a; <第2关&#xff1a;scanf 函数> 任务描述 相关知识 编程要求 测试说明 我的通关代码: 测试结果&#xff1a; <第1关&a…

You need to call SQLitePCL.raw.SetProvider()

在.NET环境中使用Entity Framework Core&#xff08;EF Core&#xff09;连接SQLite数据库时&#xff0c;报错。 使用框架 .NET8 错误信息&#xff1a; Exception: You need to call SQLitePCL.raw.SetProvider(). If you are using a bundle package, this is done by calling…

皮肤伤口分割数据集labelme格式248张5类别

数据集格式&#xff1a;labelme格式(不包含mask文件&#xff0c;仅仅包含jpg图片和对应的json文件) 图片数量(jpg文件个数)&#xff1a;284 标注数量(json文件个数)&#xff1a;284 标注类别数&#xff1a;5 标注类别名称:["bruises","burns","cu…

LeetCode 2255统计是给定字符串前缀的字符串数目

问题描述: 在字符串处理的编程任务中&#xff0c;经常会遇到判断一个字符串数组中的元素是否为另一个字符串前缀的情况。例如&#xff0c;给定一个字符串数组 words 和一个字符串 s&#xff0c;且 words[i] 和 s 都只包含小写英文字母&#xff0c;我们需要找出 words 中有多少…

JVM系列之内存区域

每日禅语 有一位年轻和尚&#xff0c;一心求道&#xff0c;多年苦修参禅&#xff0c;但一直没有开悟。有一天&#xff0c;他打听到深山中有一古寺&#xff0c;住持和尚修炼圆通&#xff0c;是得道高僧。于是&#xff0c;年轻和尚打点行装&#xff0c;跋山涉水&#xff0c;千辛万…

大腾智能CAD:国产云原生三维设计新选择

在快速发展的工业设计领域&#xff0c;CAD软件已成为不可或缺的核心工具。它通过强大的建模、分析、优化等功能&#xff0c;不仅显著提升了设计效率与精度&#xff0c;还促进了设计思维的创新与拓展&#xff0c;为产品从概念构想到实体制造的全过程提供了强有力的技术支持。然而…

css常用属性有哪些

在上篇文章我们知道了利用css选择器来对HTML进行简单装饰&#xff0c;就像做word文档一样&#xff0c;需要对哪一段落修改格式&#xff0c;就需要先选中&#xff0c;css选择器就是这意思。这格式如何修改&#xff0c;怎么放大字体&#xff0c;怎么加粗&#xff0c;怎么修改背景…

leetcode 3195.包含所有1的最小矩形面积I

1.题目要求: 2.解题步骤: class Solution { public:int minimumArea(vector<vector<int>>& grid) {//设置二维数组deque<deque<int>> row_distance;for(int i 0;i < grid.size();i){//遍历数组&#xff0c;把每行头部1的小标和尾部1的下标代…

搭建Tomcat(三)---重写service方法

目录 引入 一、在Java中创建一个新的空项目&#xff08;初步搭建&#xff09; 问题&#xff1a; 要求在tomcat软件包下的MyTomcat类中编写main文件&#xff0c;实现在MyTomcat中扫描myweb软件包中的所有Java文件&#xff0c;并返回“WebServlet(url"myFirst")”中…

创建线程 ---- 实例

1、C语言 创建线程 执行2个不同的函数&#xff1a; #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h>// 第一个线程要执行的函数 void* function1(void* arg) {printf("Function 1 is running\n");// 执行…

使用mybatisplus的逆向工程自动生成数据库中表对应的实体类、mapper、service、serviceImpl、controller等文件

使用mybatisplus的逆向工程自动生成数据库中表对应的实体类、mapper、service、serviceImpl、controller等文件 详细流程如下&#xff1a; 1、引入依赖 <dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-sta…

Linux介绍与安装CentOS 7操作系统

什么是操作系统 操作系统&#xff0c;英⽂名称 Operating System&#xff0c;简称 OS&#xff0c;是计算机系统中必不 可少的基础系统软件&#xff0c;它是 应⽤程序运⾏以及⽤户操作必备的基础环境 ⽀撑&#xff0c;是计算机系统的核⼼。 操作系统的作⽤是管理和控制计算机系…

【Linux】深入理解进程信号机制:信号的产生、捕获与阻塞

&#x1f3ac; 个人主页&#xff1a;谁在夜里看海. &#x1f4d6; 个人专栏&#xff1a;《C系列》《Linux系列》《算法系列》 ⛰️ 时间不语&#xff0c;却回答了所有问题 目录 &#x1f4da;前言 &#x1f4da;一、信号的本质 &#x1f4d6;1.异步通信 &#x1f4d6;2.信…

【西门子PLC.博途】——面向对象编程及输入输出映射FC块

当我们做面向对象编程的时候&#xff0c;需要用到输入输出的映射。这样建立的变量就能够被复用&#xff0c;从而最大化利用了我们建立的udt对象。 下面就来讲讲映射是什么。 从本质上来说&#xff0c;映射就是拿实际物理对象对应程序虚拟对象&#xff0c;假设程序对象是I0.0&…

WebRTC服务质量(04)- 重传机制(01) RTX NACK概述

WebRTC服务质量&#xff08;01&#xff09;- Qos概述 WebRTC服务质量&#xff08;02&#xff09;- RTP协议 WebRTC服务质量&#xff08;03&#xff09;- RTCP协议 WebRTC服务质量&#xff08;04&#xff09;- 重传机制&#xff08;01) RTX NACK概述 WebRTC服务质量&#xff08;…

MySQL索引的理解

MySQL与磁盘的交互 根据冯诺依曼结构体系&#xff0c;我们知道我们任何上层的应用想要去访问磁盘就必须要通过内存来访问&#xff0c;MySQL作为一款储存数据的服务&#xff0c;肯定是很多时间要用来访问磁盘。而大量访问磁盘一定会影响运行效率的在innoDB的存储引擎下为了减少…

spring集成ehcache

目录 一、前言二、使用ehcache注解方式2.1、配置2.2、使用示例三、直接读取xml方式3.1、配置3.2、使用示例3.3、结果说明一、前言 问题背景:一些业务场景中,一些数据往往是长期不变更,但数据使用较多。为了满足系统性能需要,可以借助本地缓存去使用,保证同一个JVM实例只保…

分布式全文检索引擎ElasticSearch-数据的写入存储底层原理

一、数据写入的核心流程 当向 ES 索引写入数据时&#xff0c;整体流程如下&#xff1a; 1、客户端发送写入请求 客户端向 ES 集群的任意节点&#xff08;称为协调节点&#xff0c;Coordinating Node&#xff09;发送一个写入请求&#xff0c;比如 index&#xff08;插入或更…

前端解析超图的iserver xml

前端解析超图的iserver xml const res await axios.get(url)const xmlDom new DOMParser().parseFromString(res.data, text/xml);// 获取versionconst version xmlDom.getElementsByTagNameNS(*, ServiceTypeVersion)[0].textContent// 获取layerconst layerDom xmlDom.ge…

Maven 生命周期

文章目录 Maven 生命周期- Clean 生命周期- Build 生命周期- Site 生命周期 Maven 生命周期 Maven 有以下三个标准的生命周期&#xff1a; Clean 生命周期&#xff1a; clean&#xff1a;删除目标目录中的编译输出文件。这通常是在构建之前执行的&#xff0c;以确保项目从一个…