<select id="selectByTwoId" resultMap="BaseResultMap" parameterType="java.lang.Integer">
select <include refid="Base_Column_List" />
from message
where id between #{ido,jdbcType=INTEGER} and #{idt,jdbcType=INTEGER}
</select>
DAO 方法:List selectByTwoId(Integer ido, Integer idt);
報錯:Parameter 'ido' not found. Available parameters are [0, 1, param1, param2]
MyBatis 對多參數方法的默認命名規則:
@Param 註解時:參數名為 param1, param2... 或 0, 1...(取決於版本)。#{ido} 找不到匹配參數,故報錯。// Mapper 接口
List selectByTwoId(@Param("ido") Integer ido, @Param("idt") Integer idt);
XML 保持不變,#{ido}、#{idt} 直接匹配。
<select ... parameterType="map"> ... #{ido} ... #{idt} </select>
// DAO 實現
public List selectByTwoId(Integer ido, Integer idt) {
Map params = new HashMap<>();
params.put("ido", ido);
params.put("idt", idt);
return sqlSession.selectOne("namespace.selectByTwoId", params);
}
適用於動態參數數量不固定的場景。
public class IdRange {
private Integer ido;
private Integer idt;
// getter/setter
}
// Mapper
List selectByTwoId(IdRange range);
// XML parameterType="com.xxx.IdRange"
#{ido} #{idt} 直接對應屬性
適合參數復雜、復用率高的情況。
<setting name="useActualParamName" value="true"/>,配合 Java 8 編譯參數 -parameters,可省略 @Param 直接使用形參名。多參數映射失敗核心在於 MyBatis 默認參數名 (param1/param2) 與 XML 佔位符 (ido/idt) 不匹配。添加 @Param 註解是成本最低、可讀性最好的修復方式。