Mybatis 传参:如何使用 Map 传递参数
Mybatis 传参传入 Map 可以使用以下两种方式:
- 使用@Param 注解
在 Mapper 方法的参数中使用@Param 注解指定 Map 的 key 值作为参数名,例如:
@Mapper
public interface UserMapper {
List<User> getUserList(@Param('params') Map<String, Object> params);
}
在 Mapper.xml 中可以通过 #{params.key} 来获取对应的 value 值,例如:
<select id="getUserList" resultType="com.example.User">
SELECT * FROM user
<where>
<if test="params.name != null">
AND name = #{params.name}
</if>
<if test="params.age != null">
AND age = #{params.age}
</if>
</where>
</select>
- 直接使用 Map 作为参数
在 Mapper 方法的参数中直接使用 Map 作为参数,例如:
@Mapper
public interface UserMapper {
List<User> getUserList(Map<String, Object> params);
}
在 Mapper.xml 中可以通过 #{key} 来获取对应的 value 值,例如:
<select id="getUserList" resultType="com.example.User">
SELECT * FROM user
<where>
<if test="name != null">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
原文地址: https://www.cveoy.top/t/topic/mBmI 著作权归作者所有。请勿转载和采集!