1.情景再现 Mybatis3.5.6
想通过传入的id修改表中对应数据的lastName字段值
1.1Dao接口
public interface EmployeeDao {
public void updateEmployeeById(Employee employee,Integer id);
}
1.2映射文件EmployeeMapper.xml
<mapper namespace="com.dao.EmployeeDao">
<update id="updateEmployee" >
update employee set lastName=#{employee.lastName}where id=#{id}
</update>
</mapper>
1.3测试代码
@Test
public void testUpdate()
{
SqlSessionFactory sqlSessionFactory=GetSqlSessionFactory.getInstance();
SqlSession sqlSession = sqlSessionFactory.openSession(true);
try{
EmployeeDao mapper = sqlSession.getMapper(EmployeeDao.class);
mapper.updateEmployee(new Employee(null,"test",null,null),5);
}finally{
sqlSession.close();
}
}
1.4报错
org.apache.ibatis.exceptions.PersistenceException:
Error updating database. Cause: org.apache.ibatis.binding.BindingException: Parameter ‘employee’ not found.Available parameters are [arg1, arg0, param1, param2]
The error may exist in EmployeeMapper.xml
关键是:Available parameters are [arg1, arg0, param1, param2] MyBatis3.4之前是Available parameters are [0, 1, param1, param2]
2.多参数传入的解决方法
2.1使用arg0、agr1…
原理分析:MyBatis将多个参数封装成一个HashMap,其中key为:“arg0”、“agr1”;value为传入的参数值
根据报错提示信息,修改mapper.xml为
<mapper namespace="com.dao.EmployeeDao">
<update id="updateEmployee" >
update employee set lastName=#{arg0.lastName}where id=#{arg1}
</update>
</mapper>
2.2使用Map封装传入参数
修改Dao接口为
public interface EmployeeDao {
public void updateEmployeeById(Map<?,?>map);
}
修改mapper.xml,key为映射文件中填入的名字即#{key}
<mapper namespace="com.dao.EmployeeDao">
<update id="updateEmployee" >
update employee set lastName=#{lastName}where id=#{id}
</update>
</mapper>
修改测试代码,key为映射文件中填入的名字即#{key}
public void testUpdate()
{
Map<String,Object> map=new HashMap<>();
SqlSessionFactory sqlSessionFactory=GetSqlSessionFactory.getInstance();
SqlSession sqlSession = sqlSessionFactory.openSession(true);
try{
EmployeeDao mapper = sqlSession.getMapper(EmployeeDao.class);
map.put("lastName","test");
map.put("id",5);
mapper.updateEmployee(map);
}finally{
sqlSession.close();
}
}
2.3使用注解(推荐使用)
原理分析:MyBatis将多个参数封装成一个HashMap,用注解来明确指定key值,而不是自动生成;value为传入参数。
修改Dao接口为
public interface EmployeeDao {
public void updateEmployee(@Param("employee")Employee employee,@Param("id")Integer id);
}
修改mapper.xml,这种方法参数名简单直观,即注解中的参数名
<mapper namespace="com.dao.EmployeeDao">
<update id="updateEmployee" >
update employee set lastName=#{employee.lastName}where id=#{id}
</update>
</mapper>
测试代码
public void testUpdate()
{
SqlSessionFactory sqlSessionFactory=GetSqlSessionFactory.getInstance();
SqlSession sqlSession = sqlSessionFactory.openSession(true);
try{
EmployeeDao mapper = sqlSession.getMapper(EmployeeDao.class);
mapper.updateEmployee(new Employee(null,"test",null,null),5);
}finally
{
sqlSession.close();
}
}
本文详细介绍了在MyBatis 3.5.6中如何处理多参数传入的问题,包括使用arg0、arg1的方式,使用Map封装参数以及推荐的注解方法。针对报错'Parameter ‘employee’ not found',提出了修改映射文件和接口的解决方案,并提供了测试代码以验证正确性。最后,强调了注解方式的简洁性和易读性,推荐在实际开发中使用。
213

被折叠的 条评论
为什么被折叠?



