nested exception is org.apache.ibatis.binding.BindingException: Parameter 'XXX' not found報錯
今天遇到mybatis的報錯,搞了好久才搞懂,相信也能解決大部分人的報錯。
報錯資訊如下:
org.mybatis.spring.MyBatisSystemException:
nested exception is org.apache.ibatis.binding.BindingException: Parameter 'roleIds' not found. Available parameters are [0, 1, param1, param2]
出現上面異常的原因:
*mapper.xml對映沒有得到傳入的引數,這個時候需要在DAO變化傳參。
在使用mybatis開發的時候,有時候需要傳入
@Param
用註解來簡化xml配置的時候,@Param註解的作用是給引數命名,引數命名後就能根據名字得到引數值,正確的將引數傳入sql語句中。簡單說就是@Param("orId2") String orId1 在啟動時生成一個orId2的屬性,把引數orId1的值賦給orId2,這樣就可以在申請了中使用#{orId2} 或者${orId2}獲取變數,如果不配置@Param("orId2"),就不會有orId2屬性,只能用預設的#{orId1}來取值。
下面對比一下錯誤的和正確的傳參方式:
錯誤:
int insertObject(Integer userId,Integer[] roleIds);
正確:
int insertObject(@Param("userId")Integer userId,@Param("roleIds")Integer[] roleIds);
使用@Param注意事項:
使用@Param註解
1.當以下面的方式進行寫SQL語句時:
@Select("select column from table where userid = #{userid} ")
public int selectColumn(int userid);
2.當你使用了使用@Param註解來宣告引數時,如果使用 #{} 或 ${} 的方式都可以。
@Select("select column from table where userid = ${userid} ")
public int selectColumn(@Param("userid") int userid);
3.當你不使用@Param註解來宣告引數時,必須使用使用 #{}方式。如果使用 ${} 的方式,會報錯。
@Select("select column from table where userid = ${userid} ")
public int selectColumn(@Param("userid") int userid);
不使用@Param註解
不使用@Param註解時,引數只能有一個,並且是Javabean。在SQL語句裡可以引用JavaBean的屬性,而且只能引用JavaBean的屬性。
// 這裡id是user的屬性
@Select("SELECT * from Table where id = ${id}")
Enchashment selectUserById(User user);
例項一 @Param註解單一屬性
dao層示例
Public User selectUser(@param(“userName”) String name,@param(“userpassword”) String password);
xml對映對應示例:
<select id=" selectUser" resultMap="BaseResultMap">
select * from user_user_t where user_name = #{userName,jdbcType=VARCHAR} and user_password=#{userPassword,jdbcType=VARCHAR}
</select>
注意:採用#{}的方式把@Param註解括號內的引數進行引用(括號內參數對應的是形參如 userName對應的是name);
例項二 @Param註解JavaBean物件
dao層示例
public List<user> getUserInformation(@Param("user") User user);
xml對映對應示例:
<select id="getUserInformation" parameterType="com.github.demo.vo.User" resultMap="userMapper">
select
<include refid="User_Base_Column_List" />
from mo_user t where 1=1
<!-- 因為傳進來的是物件所以這樣寫是取不到值得 -->
<if test="user.userName!=null and user.userName!=''"> and t.user_name = #{user.userName} </if>
<if test="user.userAge!=null and user.userAge!=''"> and t.user_age = #{user.userAge} </if>
</select>