MyBatis几种SQL写法

ops/2024/11/13 4:11:43/

目录

1. 批量操作:通过标签支持批量插入

2. 批量操作:通过标签支持批量更新

3. 批量操作:通过标签支持批量删除

4. 动态SQL

3. 多条件分支查询

4. SQL语句优化:使用标签避免多余的AND或OR关键字。

5. 注解方式使用MyBatis

6. 一对多

7. 多对一:每个评论(Comment)都属于一篇文章(Article),并且每篇文章可以有多个评论。

8. MyBatis-Plus集成


1. 批量操作:通过<foreach>标签支持批量插入

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

2. 批量操作:通过<foreach>标签支持批量更新

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

3. 批量操作:通过<foreach>标签支持批量删除

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

4. 动态SQL

<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. 多条件分支查询

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

4. SQL语句优化:使用<trim>标签避免多余的ANDOR关键字。

<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>

5. 注解方式使用MyBatis

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);
}

6. 一对多

<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>

7. 多对一:每个评论(Comment)都属于一篇文章(Article),并且每篇文章可以有多个评论。

<?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.example.mapper.ArticleMapper"><!-- 定义 Comment 的 resultMap --><resultMap id="commentWithArticleMap" type="Comment"><id property="id" column="comment_id"/><result property="content" column="comment_content"/><result property="createTime" column="comment_create_time"/><association property="article" javaType="Article"><id property="id" column="article_id"/><result property="title" column="article_title"/><result property="content" column="article_content"/></association></resultMap><!-- 定义 Article 的 resultMap --><resultMap id="articleWithCommentsMap" type="Article"><id property="id" column="article_id"/><result property="title" column="article_title"/><result property="content" column="article_content"/><collection property="comments" ofType="Comment" resultMap="commentWithArticleMap"/></resultMap><!-- 查询文章及其评论列表 --><select id="getArticleWithComments" resultMap="articleWithCommentsMap">SELECT a.id as article_id,a.title as article_title,a.content as article_content,c.id as comment_id,c.content as comment_content,c.create_time as comment_create_timeFROM article aLEFT JOIN comment c ON a.id = c.article_idWHERE a.id = #{articleId}</select></mapper>

8. 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));}
}


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

相关文章

卷积神经网络基础

卷积神经网络基础 一、卷积神经网络的提出 卷积神经网络的提出LeNet-5 二、卷积神经网络关键部件 卷积神经网络中的四个主要操作一个简单的卷积神经网络 三、卷积神经网络训练过程 1、前向传播阶段2、反向传播阶段训练过程 四、典型卷积神经网络 图像识别(分类)算法-LeNet-5 …

ubuntu 22.04 防火墙 ufw

Ubuntu&#xff08;22.04&#xff09;云主机SSH安全加固 https://blog.csdn.net/qq_44846097/article/details/141098092 ubuntu22.04防火墙策略 https://blog.csdn.net/sunyuhua_keyboard/article/details/139493464 Ubuntu 22.04 防火墙设置和开放端口命令 https://blog.c…

易考八股文之谈谈对sentinel的理解和作用?

在Java中&#xff0c;Sentinel&#xff08;哨兵&#xff09;是一个非常重要的组件&#xff0c;尤其在分布式服务架构和微服务环境中&#xff0c;它扮演着流量控制、熔断降级以及系统负载保护的关键角色。以下是对Sentinel的理解和作用的详细阐述&#xff1a; 一、Sentinel的理…

shell--常用命令

命令执行失败之后的操作 teee --version || { echo "tee command not found"; exit 1; } /dev/null /dev/null 对应的是一个空设备文件&#xff0c;任何写入这个文件的数据都将立即被销毁&#xff0c;而不是写到磁盘上。 if dpkg -s software-properties-common &g…

将数组中的数据反向输出(数组,函数)

将数组中的数据反向输出&#xff0c;用数组名作函数参数 swap函数是用来实现数组中元素前后的调换&#xff0c;用这种方式来实现数组中元素的逆序输出 #include <stdio.h> #include <stdlib.h> void swap(int m[],int n); int main() {int a[]{1,2,3,4,5,6,7,8,9,…

VisionPro —— CogSobelEdgeTool边缘提取工具

此工具可隔离和增强图像中的边缘信息。此编辑控件用于指定 magnitude scaling factor&#xff0c;选择 post-processing operation&#xff0c;以及查看视觉工具结果。 边缘幅度图像&#xff1a;基于输入图像中像素的边缘幅度的输出图像。 较大的边缘将在输出图像中生成具有较…

元岭村停车场的收费情况探寻

​虽然我居住在石岩园岭村范围&#xff0c;但是我没有把车子停到园岭村&#xff08;村着有些标语是园岭村有些是元岭村&#xff09;。主要是因为村里停车太需要技术了&#xff0c;不仅村里开车路况和人流复杂&#xff0c;而且停车位也很有限&#xff0c;车子一般是村里哪里有空…

K8s使用nfs

改动点 ip和路径改为自己的 --- apiVersion: v1 kind: ServiceAccount metadata:name: nfs-client-provisioner# replace with namespace where provisioner is deployednamespace: nfs-client --- kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 metadata:nam…