温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java mybatis如何动态sql

发布时间:2026-09-23 06:53:38 来源:亿速云 阅读:97 作者:小樊 栏目:编程语言

在 MyBatis 中,“动态 SQL”指的是根据条件动态拼接 SQL 语句,常用于查询、更新等场景。MyBatis 提供了一些标签来实现动态 SQL。

下面按常用方式 + 示例说明(基于 XML 方式,最常用)。


一、常用动态 SQL 标签

标签 作用
<if> 条件判断
<where> 自动处理 WHERE 和多余 AND/OR
<set> 更新时自动处理 SET 和逗号
<choose><when><otherwise> 类似 if-else
<foreach> 遍历集合(IN、批量)
<trim> 自定义前缀/后缀处理

二、<if> + <where>(最常用)

Mapper 接口

List<User> selectUser(User user);

XML

<select id="selectUser" resultType="User">
    SELECT * FROM user
    <where>
        <if test="name != null and name != ''">
            AND name = #{name}
        </if>
        <if test="age != null">
            AND age = #{age}
        </if>
    </where>
</select>

✅ 特点:

  • <where> 会自动去掉多余的 AND
  • 条件为空时不会报错

三、<set> 动态更新

<update id="updateUser">
    UPDATE user
    <set>
        <if test="name != null">
            name = #{name},
        </if>
        <if test="age != null">
            age = #{age},
        </if>
    </set>
    WHERE id = #{id}
</update>

✅ <set> 会自动去掉最后一个逗号


四、<choose>(if / else if / else)

<select id="selectUser" resultType="User">
    SELECT * FROM user
    <where>
        <choose>
            <when test="name != null">
                AND name = #{name}
            </when>
            <when test="age != null">
                AND age = #{age}
            </when>
            <otherwise>
                AND status = 1
            </otherwise>
        </choose>
    </where>
</select>

五、<foreach>(IN / 批量)

1️⃣ IN 查询

<select id="selectByIds" resultType="User">
    SELECT * FROM user
    WHERE id IN
    <foreach collection="ids" item="id" open="(" close=")" separator=",">
        #{id}
    </foreach>
</select>

2️⃣ 批量插入

<insert id="batchInsert">
    INSERT INTO user(name, age) VALUES
    <foreach collection="list" item="u" separator=",">
        (#{u.name}, #{u.age})
    </foreach>
</insert>

六、<trim>(更灵活)

<trim prefix="WHERE" prefixOverrides="AND | OR">
    <if test="name != null">
        AND name = #{name}
    </if>
</trim>

七、注解方式(不推荐复杂 SQL)

@Select({
    "<script>",
    "SELECT * FROM user",
    "<where>",
    "<if test='name != null'> AND name = #{name} </if>",
    "</where>",
    "</script>"
})
List<User> selectUser(@Param("name") String name);

八、常见注意点 ⚠️

  1. test 中是 OGNL 表达式
    • 基本类型:age != null
    • String:name != null and name != ''
  2. 多参数一定要用 @Param
  3. 动态 SQL 尽量写在 XML 中,易维护

如果你愿意,我可以:

  • ✅ 给你一个完整 MyBatis 动态 SQL 示例
  • ✅ 讲 MyBatis-Plus 的动态 SQL
  • ✅ 对比 XML vs 注解

你更想看哪一种?

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手