• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

mybatis 搞代码 4年前 (2022-01-09) 25次浏览 已收录 0个评论

最近写了几个非常简单的接口(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-custome本文来源gaodaimacom搞#^代%!码&网(r-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条数据如下:

1. name:li cid=3

2. name:ly cid=3

这两条数据都符合update匹配条件,但是第1条数据不需要修改,只是更改了第2条数据的name值,最终返回值依旧为2

delete对应方法返回值为删除的数据条数

而KeyProperty、useGeneratedKeys这两个属性是用来设置user对象中的id值(id为自增主键)的。

User user = new User();
user.setAgeType(1); 
user.setCityId(1);
addUser(user);
System.out.println(user.id);

如上,我们并没有设置user对象的id值,但是却能输出正确的id。

当然,使用 selectKey也能达到同样的效果

补充知识:Mybatis Update操作 返回值修改为受影响条数

到底 update 返回值代表什么呢?我们来验证一下便知道了,假设有如下一张表以及两条数据:

我们来编写一个简单的单元测试用例来验证下,首先使用 mybatis 简单的写个 mapper 进行更新操作,其中 xml 中的内容为:

数据库连接配置为:


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:解决Mybatis中mapper.xml文件update,delete及insert返回值问题

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址