如何编写含List<String>与Long双参数的MyBatis XML Mapper?遇启动异常
解决MyBatis双参数Mapper的绑定异常问题
你遇到的这个问题,核心原因是MyBatis无法自动识别多参数方法里的参数名称,导致XML映射文件里的参数引用找不到对应的实参。下面给你两种靠谱的解决方法,推荐第一种,可读性和维护性都更好:
方法一:使用@Param注解显式命名参数
这是最常用也最清晰的方案,给Mapper接口的每个参数加上@Param注解指定别名,这样XML里就能直接通过别名引用参数了。
修改后的Java Mapper代码:
import org.apache.ibatis.annotations.Param; import java.util.List; public interface UserLogMapper { List<UserLog> batchSelect(@Param("userList") List<String> userList, @Param("mallId") Long mallId); }
修改后的XML Mapper代码:
<select id="batchSelect" resultMap="ResultMap"> select id, user_id, mall_id, log, log_type from user_log where user_id in ( <foreach collection="userList" index="index" item="item" separator=","> #{item,jdbcType=VARCHAR} </foreach> ) and mall_id = #{mallId,jdbcType=BIGINT} </select>
这里关键点是:
- 用
@Param("userList")给List参数命名,XML里foreach的collection属性就对应这个名称 mallId参数也通过@Param命名,XML里直接用#{mallId}引用
方法二:使用MyBatis默认的参数命名(不推荐)
如果不想加注解,MyBatis会给多参数默认命名为param1、param2(低版本可能是arg0、arg1),你也可以直接用这些名称:
XML Mapper修改如下:
<select id="batchSelect" resultMap="ResultMap"> select id, user_id, mall_id, log, log_type from user_log where user_id in ( <foreach collection="param1" index="index" item="item" separator=","> #{item,jdbcType=VARCHAR} </foreach> ) and mall_id = #{param2,jdbcType=BIGINT} </select>
这种方式虽然能解决问题,但参数名称不够直观,后期维护起来容易搞混,所以更推荐第一种方案。
另外补充个小细节:如果你的Spring Boot项目开启了编译参数-parameters(Maven或Gradle配置),MyBatis可以直接识别方法的原生参数名,不用加@Param也能直接用userList和mallId,不过显式加@Param的兼容性更好,跨版本也不容易出问题。
内容的提问来源于stack exchange,提问作者linrongbin
相关产品推荐
相关产品推荐

