執行 MyBatis 查詢時拋出異常:
Parameter 'params' not found. Available parameters are [param1, page]
public int queryCount(@Param("page") CompanyForm page) throws DaoException;
@Override
public int queryCount(CompanyForm page) throws ServiceException {
try {
return companyExtMapper.queryCount(page);
} catch (Exception e) {
throw new ServiceException(e.getMessage(), e);
}
}
<select id="queryCount" resultType="java.lang.Integer"
parameterType="classroom.common.form.CompanyForm">
select count(1) from company
<include refid="condition" />
</select>
核心問題:Mapper XML 中引用了 page 參數的屬性(如 page.someProperty),但實際傳遞的參數名稱為 param1(MyBatis 默認命名),而非預期的 page。
原因鏈:
@Param("page") 指定參數名為 "page"parameterType 宣告為具體類型,導致 MyBatis 嘗試直接訪問對象屬性#{page.property} 卻未正確綁定參數名,會找不到 "page"在 XML 中引用參數時,嚴格使用註解指定的名稱:
<select id="queryCount" resultType="java.lang.Integer">
select count(1) from company
<where>
<if test="page != null and page.someProperty != null">
and some_column = #{page.someProperty}
</if>
</where>
</select>
讓 MyBatis 自動推斷參數類型,直接使用 @Param 綁定的名稱:
<select id="queryCount" resultType="java.lang.Integer">
select count(1) from company
<include refid="condition" />
</select>
若只有一個參數,可移除 @Param,MyBatis 會將對象屬性直接映射:
// 接口
public int queryCount(CompanyForm page) throws DaoException;
// XML 中直接訪問屬性
<if test="someProperty != null">...#{someProperty}...</if>
@Param 指定名稱parameterType 和 @Param 混淆映射關係