该项目day2中,检查项分页的映射文件设置如下:
<select id="selectByCondition" parameterType="string"
resultType="com.itheima.pojo.CheckItem">
select * from t_checkitem
<if test="value != null and value.length > 0">
where code = #{value} or name = #{value}
</if>
</select>
为什么parameterType="string"时,下面的变量名为value?
解释:
一句话解释:这是mybatis的规定,传入String类型时,参数写string,下面变量名写value。
对于对象类型的变量,mybatis会去传入的参数类型的类里面去找相应的getter,也就是说传入参数为string时,mybatis会拿着程序员设定的变量名去String类里面去找相应的getter——如果设定的变量名为ok,mybatis就会去String里找ok的getter,这显然是没有的。
除此之外,还有两种方法将string的参数传入,一是使用_parameter作为参数名,二是在接口参数里加上mybatis中的@param注解。注意,方法二中导入的是mybatis的包(不过路径中写作ibatis)。
方法一的例:
<select id="selectByCondition" parameterType="string"
resultType="com.itheima.pojo.CheckItem">
select * from t_checkitem
<if test="_parameter != null and _parameter.length > 0">
where code = #{_parameter} or name = #{_parameter}
</if>
</select>
方法二的例:
public Page<CheckItem> selectByCondition(@Param("ok")String queryString);
<select id="selectByCondition" parameterType="string"
resultType="com.itheima.pojo.CheckItem">
select * from t_checkitem
<if test="ok != null and ok.length > 0">
where code = #{ok} or name = #{ok}
</if>
</select>
题外话:
在mybatis3.5.9(写作时最新版)的文档中说明,
鉴于参数类型(parameterType)会被自动设置为
int
,这个参数可以随意命名。原始类型或简单数据类型(比如Integer
和String
)因为没有其它属性,会用它们的值来作为参数。
也就是说传入参数为int时,可以随意命名,而简单数据类型没有提到命名规则。