温馨提示×

温馨提示×

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

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

Dynamic SQL怎么传参数

发布时间:2026-09-08 23:22:11 来源:亿速云 阅读:83 作者:小樊 栏目:数据库

MyBatis(动态 SQL) 中,传参数有多种方式,常见如下:


1️⃣ 单个基本类型参数(自动绑定)

User selectById(Integer id);
<select id="selectById" resultType="User">
  SELECT * FROM user WHERE id = #{id}
</select>

✅ 参数名任意(推荐与 #{} 一致)


2️⃣ 多个基本类型参数(@Param)

List<User> selectByCondition(
    @Param("name") String name,
    @Param("age") Integer age);
<select id="selectByCondition">
  SELECT * FROM user
  WHERE name = #{name}
  AND age = #{age}
</select>

3️⃣ 对象参数(最常用)

User selectByUser(User user);
<select id="selectByUser">
  SELECT * FROM user
  WHERE name = #{name}
  AND age = #{age}
</select>

✅ 直接写对象属性名


4️⃣ Map 参数

Map<String, Object> map = new HashMap<>();
map.put("name", "Tom");
map.put("age", 18);
<select id="selectByMap">
  SELECT * FROM user
  WHERE name = #{name}
  AND age = #{age}
</select>

5️⃣ 动态 SQL 中传参(if / foreach)

if 示例

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

foreach 示例(List 传参)

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

6️⃣ #{} 与 ${} 区别(重要)

写法 说明
#{} 预编译(安全,防 SQL 注入)✅
${} 字符串拼接(有注入风险)⚠️

❌ 不推荐:

ORDER BY ${column}

✅ 仅用于表名 / 列名动态


总结

✅ 基本参数 → 直接 #{}
✅ 多参数 → @Param
✅ 复杂条件 → 对象 / Map
✅ 动态 SQL → if / choose / foreach

如果你用的是 Spring Boot / MyBatis-Plus / XML / 注解,可以告诉我,我可以给你更具体的示例。

向AI问一下细节

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

AI