解决Mybatis中mapper.xml文件update,delete及insert返回值问题


本文整理自网络,侵删。

最近写了几个非常简单的接口(CRUD),在单元测试的时候却出了问题,报错如下:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'messageListener': Unsatisfied dependency expressed through field 'reviewCheckInfoService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'reviewCheckInfoServiceImpl': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'reviewCheckInfoDao' defined in file [/Users/a1475368628/IdeaProjects/baby-customer-parent/baby-customer-service/target/classes/com/dianping/baby/customer/reviewcheck/dao/ReviewCheckInfoDao.class]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:

PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'sqlSessionFactory' threw exception; nested exception is java.lang.NullPointerException

经过仔细排查,问题的原因出在sql的xml配置文件出错,直接原因是在update中错误的使用了KeyProperty、useGeneratedKeys。

学习相关知识之后,在这里仔细总结一下。

在Mybatis的xml配置文件中,insert和update中可以设置属性KeyProperty、useGeneratedKeys,用来返回自增主键的值。

在DAO层中有一个方法:

public int addUser(@Param("user")User user);

对应的xml文件中为:

<insert id="addUserType="map" keyProperty="user.id" useGeneratedKeys="true">
 INSERT INTO a_user
 (
  AgeType,
  CityId,
  AddTime,
  UpdateTime
  )
  VALUES
  (
  #{user.ageType},
  #{user.cityId},
  NOW(),
  NOW()
  )
</insert>

我错误的认为是addUser()这个方法会返回插入记录的自增id值,结果测试的时候,addUser()方法返回值始终是1。仔细学习后得知:

insert对应的方法返回值为插入数据库的条数(如上,每次插入一条数据,所以每次addUser()都是返回1)

update对应的方法返回值为匹配数据库的条数(不论最终是否对数据进行了修改,只要某条记录符合匹配条件,返回值就加1)

举例:

update table_name set name="li" where cid = 3.

假如数据库中有2条数据如下:

阅读剩余部分

相关阅读 >>

php sql之where语句生成器

mybatis中防止sql注入讲解

sql学习第一天——sql 练习题(建表sql语句)

如何得到数据库中所有表名 表字段及字段中文描述

sql server数学函数的简单总结

sqlserver2019 数据库环境搭建与使用的实现

python orm框架sqlalchemy学习笔记之数据查询实例

postgresql教程(十五):系统表详解

sqlserver分页的两种写法分别介绍

sql cast,convert,quotename,exec 函数学习记录

更多相关阅读请进入《sql》频道 >>


数据库系统概念 第6版
书籍

数据库系统概念 第6版

机械工业出版社

本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...