在Mybatis中定义mapper信息有两种方式:1·利用xml文件写一个对应的包含mapper信息的配置文件;2·定义一个mapper接口和一些相应的操作方法。
我使用的是第二种方法:有接口,有实现类,以一个方法为例:更新密码(需要传递:用户名,旧密码,新密码三个参数)我的代码如下:
【Dao层实现方法:】
@SuppressWarnings("unchecked")
public int modifyPwd(Stringphone_id, String oldPwd, StringuserPwd2){
returnclientMapper.modifyPwd(phone_id,oldPwd,userPwd2);
}
【Mapper接口方法:】
public interface ClientMapper {
/*
* 修改密码 ---贾丽敏 2016年3月22日16:15:39
*/
public int modifyPwd(String phone_id, String oldPwd,String userPwd2);
}
【Mapper实现方法:】
<updateid="modifyPwd"parameterType="java.lang.String">
update
client
setpassword=#{userPwd2,jdbcType=VARCHAR}
wherephone_id=#{phone_id,jdbcType=VARCHAR}
andpassword=#{oldPwd,jdbcType=VARCHAR}
</update>
按照我之前做的select查询(条件是一个,测试已成功),这完全没有问题的,可是.....
mybatis异常:org.apache.ibatis.binding.BindingException:Parameter 'phone_id' not found. Available param
真的是纳闷了半天,为啥呢,我明明在Dao中已经定义了参数phone_id,为什么说没有发现该参数呢?最后还是上网解决了该问题。
网上这么说:
在MyBaits的select,insert,update,delete这些元素中,属性parameterType有基本数据类型和java复杂数据类型
- 基本数据类型:包含int,String,date等,基本数据类型作为传参,只能传入一个。通过#{参数名}即可获取
- 复杂数据类型:包含java实体类,Map,通过#{属性名}或#{map的keyname}即可获取传入的值
那这样,就很明显知道自己哪里错了,自己传了三个参数,都是基本数据类型,所以,是我自己想当然了。
那么,我就要用复杂数据类型来做了:采用Map传多参数。详见如下:
【Dao层实现方法:】
@SuppressWarnings("unchecked")
public int modifyPwd(Stringphone_id, String oldPwd, StringuserPwd2){
//把参数手动封装在Map中
Map map = new HashMap();
map.put("phone_id",phone_id);
map.put("oldPwd", oldPwd);
map.put("userPwd2",userPwd2);
return clientMapper.modifyPwd(map);
}
【Mapper接口方法:】
/*
* 修改密码 ---贾丽敏 2016年3月22日16:15:39
*/
public int modifyPwd(Map map);
【Mapper实现方法:】
<updateid="modifyPwd"parameterType="java.util.Map">
update
client
setpassword=#{userPwd2,jdbcType=VARCHAR}
wherephone_id=#{phone_id,jdbcType=VARCHAR}
andpassword=#{oldPwd,jdbcType=VARCHAR}
</update>
这是传递多个参数的一种方法,其它两种分别如下:
【1】
DAO层函数方法:
public int modifyPwd(String phone_id, String oldPwd,String userPwd2){
returnclientMapper.modifyPwd(phone_id,oldPwd,userPwd2);
}
对应的Mapper.xml
<update id="modifyPwd">
update
client
setpassword=#{2}
wherephone_id=#{0}
andpassword=#{1}
</update>
【2】使用注解的方式:
DAO层函数方法:
public int modifyPwd(String phone_id, String oldPwd,String userPwd2){
returnclientMapper.modifyPwd(@param(value="phone_id") Stringphone_id,@param(value="oldPwd") StringoldPwd,@param(value="userPwd2") StringuserPwd2);
}
对应的Mapper.xml:
<updateid="modifyPwd">
update
client
setpassword=#{userPwd2,jdbcType=VARCHAR}
wherephone_id=#{phone_id,jdbcType=VARCHAR}
andpassword=#{oldPwd,jdbcType=VARCHAR}
</update>
大概就是这些内容,重点就是知道中间的那两个基本类型和复杂类型的传参规则就ok了,其它都一样的了!重在积累.......