全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-20 6 分钟 ✍️ juanwangdev

单参数传递

单参数传递是 MyBatis 最基础的参数接收方式。

基本类型参数

XML
<select id="selectById" resultType="com.example.entity.User">
    SELECT * FROM user WHERE id = #{id}
</select>
Java
// Mapper 接口
User selectById(Integer id);

// 调用
User user = mapper.selectById(1);

MyBatis 自动将 #{id} 替换为实际参数值,使用 PreparedStatement 防 SQL 注入。

String 类型参数

XML
<select id="selectByUsername" resultType="com.example.entity.User">
    SELECT * FROM user WHERE username = #{username}
</select>
Java
User selectByUsername(String username);

注意:单参数时,#{} 中名称可任意填写,MyBatis 自动识别参数值。

参数索引与命名

XML
<!-- 以下三种写法等价 -->
<select id="selectById">
    SELECT * FROM user WHERE id = #{id}
</select>

<select id="selectById">
    SELECT * FROM user WHERE id = #{0}
</select>

<select id="selectById">
    SELECT * FROM user WHERE id = #{param1}
</select>

要点总结

  • 单参数使用 #{} 占位符,MyBatis 自动识别参数值
  • 支持基本类型、String 类型直接传递
  • #{} 中名称可任意填写,或使用索引 #{0}#{param1}
  • PreparedStatement 预编译防 SQL 注入

📝 发现内容有误?点击此处直接编辑

← 上一篇 resultMap 结果映射
下一篇 → 基本类型结果集
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库