SpringBoot整合Mybatis注解版---update时出现的问题
问题描述:
1、sql建表语句
DROP TABLE IF EXISTS `department`; CREATE TABLE `department` ( `id` int(11) NOT NULL AUTO_INCREMENT, `departmentName` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2、Repository层使用注解方式,
语句如下:
@Update("UPDATE department SET departmentName=#{department.departmentName} WHERE id = #{id}") public Integer updateEmp(Integer id, Department department);
显示错误信息:
org.apache.ibatis.binding.BindingException: Parameter 'department' not found. Available parameters are [arg1, arg0, param1, param2]
由错误信息得知,参数发现不了,或者解析不了,可以用 arg1, arg0, param1, param2替换,假如我们不是用POJO对象Department进行传参,
而是使用单个字段分别进行传值,那么结果。
@Update("UPDATE department SET departmentName=#{param2} WHERE id = #{param1}") public Integer updateEmp( Integer id, String departmentName);
但是随着字段增多,我们使用POJO对象Department进行传参,需要在传过来的参数上添加注解,起别名的方式,获得参数,sql语句中通过对象名.属性名方式
获得参数的值,结果也是成功。
更改后得语句:
controller: @PostMapping("/dept/{id}") public Integer updateEmp(@PathVariable("id") Integer id,@Param("departmentName") Department department) { return departmentService.updateEmp(id,departmentName); } ------------------------- service: public Integer updateEmp(Integer id,Department department) {
Department dep = new Department(id,department); return departmentMapper.updateEmp(id,dep); } ------------------------- repository: @Mapper public interface DepartmentMapper { @Update("UPDATE department SET departmentName=#{department.departmentName} WHERE id = #{id}") public Integer updateEmp(@Param("id") Integer id,@Param("department") Department department); }