单参数传递
单参数传递是 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 注入
📝 发现内容有误?点击此处直接编辑