MyBatis几种SQL写法

目录

[1. 批量操作:通过标签支持批量插入](#1. 批量操作:通过标签支持批量插入)

[2. 批量操作:通过标签支持批量更新](#2. 批量操作:通过标签支持批量更新)

[3. 批量操作:通过标签支持批量删除](#3. 批量操作:通过标签支持批量删除)

[4. 动态SQL](#4. 动态SQL)

[3. 多条件分支查询](#3. 多条件分支查询)

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

[5. 注解方式使用MyBatis](#5. 注解方式使用MyBatis)

[6. 一对多](#6. 一对多)

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

[8. MyBatis-Plus集成](#8. MyBatis-Plus集成)


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

java 复制代码
<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>标签支持批量更新++

java 复制代码
<update id="batchUpdate" parameterType="java.util.List">
    <foreach collection="list" item="item" separator=";">
        UPDATE user
        SET username = #{item.username}, email = #{item.email}
        WHERE id = #{item.id}
    </foreach>
</update>

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

java 复制代码
<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

java 复制代码
<select id="findUsers" resultType="User">
    SELECT * FROM user
    WHERE 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. 多条件分支查询

java 复制代码
<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关键字。

java 复制代码
<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

java 复制代码
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. 一对多

java 复制代码
<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_time
    FROM user u
    LEFT JOIN orders o ON u.id = o.user_id
    WHERE u.id = #{userId}
</select>

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

java 复制代码
<?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_time
        FROM article a
        LEFT JOIN comment c ON a.id = c.article_id
        WHERE a.id = #{articleId}
    </select>

</mapper>

8. MyBatis-Plus集成

java 复制代码
@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));
    }
}
相关推荐
那个失眠的夜14 分钟前
RESTful 语法规范 核心注解详解
java·spring·mvc·mybatis
无巧不成书021833 分钟前
Windows环境变量故障排查:记事本BOM头导致配置失效终极解决方案 | 零基础全流程指南
windows·批处理脚本故障·windows故障排查·windows记事本·bom头·utf-8 bom·环境变量读取失效 环境变量配置
在屏幕前出油1 小时前
08. ORM——快速开始
数据库·后端·python·sql·pycharm·orm
lzhdim1 小时前
SQL 入门 11:日期时间格式化、IF、CASE的使用
数据库·sql
FuckPatience1 小时前
Visual Studio的配置管理器
windows·visual studio
上海云盾-小余1 小时前
Web 业务常见 SQL 注入攻击原理详解及 WAF 防护部署实战教程
前端·数据库·sql
疯狂打码的少年1 小时前
说透 SQL 连接:一文讲清 INNER JOIN、LEFT JOIN、RIGHT JOIN、FULL JOIN
数据库·sql
Chockmans2 小时前
春秋云境CVE-2008-4732
sql·安全·web安全·系统安全·安全威胁分析·春秋云境·cve-2008-4732
REDcker2 小时前
跨平台编译详解 工具链配置与工程化实践
linux·c++·windows·macos·c·跨平台·编译
私人珍藏库2 小时前
[吾爱大神原创工具] 桌面挂件-世界时钟+待办提醒 v1.0 专为出海贸易而设计
windows·工具·软件·win·多功能