版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/xiao_dondon/article/details/79653226
最近写了几个非常简单的接口(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条数据如下:
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也能达到同样的效果