1.关于@Param注解
@Param是mybatis提供的注解,它在包下,是作用在Dao层的注解,传递参数,从而可以与SQL中的的字段名相对应,一般在2=<参数数<=5时使用最佳。
源码:
package ;
import ;
import ;
import ;
import ;
import ;
@Documented
@Retention()
@Target({})
public @interface Param {
String value();
}
2.应用@Param
dao层实例,ssm框架的mapper中
Page getPageByKey(@Param(value = "status") Integer status,
@Param(value = "key") String key);
xml映射
<!--根据key获得-->
<select resultType="">
SELECT
<include ref/>
FROM
<include ref/>
<where>
<if test="status!=null">
page_status=#{status} AND
</if>
page_key=#{key}
</where>
</select>
@Param的使用,加与不加
若是mapper层忘记使用@Param
Page getPageByKey(Integer status, String key);
则会报错:
严重: () for servlet [ForestBlog] in context with path [] threw exception [Request processing failed; nested exception is : nested exception is : Parameter ‘status’ not found. Available parameters are [0, 1, param1, param2]] with root cause
: Parameter ‘status’ not found. Available parameters are [0, 1, param1, param2]
因为有两个参数,mybaits没有办法进行区分,抛出异常。
其实都是接口的参数命名导致mybatis参数绑定出错引起的。默认情况下mybatis把参数按顺序转化为[0, 1, param1, param2],也就是说#{0} 和 #{param1} 是一样的,都是取第一个参数,以此类推。
下面经过实验验证,首先分两种情况:
- 使用if判断
在xml的SQL映射中有if判断,那么mapper接口就需要@Param对参数进行标明,比如下面例子,尽管只有一个参数传入,但因为sql语句中有if语句对其进行判断,就需要添加
mapper接口:
/**
* 获得公告列表
* @param status
* @return
*/
List<Notice> listNotice(@Param(value = "status") Integer status);
xml文件
<!--获取公告列表-->
<select resultType="">
SELECT
<include ref/>
FROM <include ref/>
<where>
<if test="status!=null">
notice_status=#{status}
</if>
</where>
ORDER BY notice_status ASC, notice_order DESC, notice_id ASC
</select>
- 没有使用if判断
这种情况下也分为两种情况:
(1)接口参数只有一个,不管接口参数是什么,这时便不需要再进行判断,Mybatis会自动进行匹配
(2)当接口参数大于一个的时候,mybatis的参数集就是上边说的默认值[0, 1, param1, param2],如果你不用默认值,就需要加上@Param注解起别名。一旦加了注解,mybatis的参数集就和第一种情况一样了,这个时候也就不再区分是否使用if判断。