keyProperty="id" 和useGeneratedKeys="true"作用

Posted zenghuilong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了keyProperty="id" 和useGeneratedKeys="true"作用相关的知识,希望对你有一定的参考价值。

在使用mybatis时,常常会出现这种需求:
当主键id是自增的情况下,添加一条记录的同时,其主键id是不能使用的,当我们取出主键id的值发现id为null,但是有时我们需要该主键,这时我们该如何处理呢?
这时我们只需要在其对应xxxmapper.xml中加入以下属性即可:
useGeneratedKeys=”true” keyProperty=”id”

 1 <insert id="insertSelective" parameterType="com.xxx.dataobject.UserDo" keyProperty="id" useGeneratedKeys="true">

2 ............

3 </insert> 

 主要是在主键是自增的情况下,添加成功后可以直接使用主键值,其中keyProperty的值是对象的属性值不是数据库表中的字段名

 




以上是关于keyProperty="id" 和useGeneratedKeys="true"作用的主要内容,如果未能解决你的问题,请参考以下文章

MyBatis Mapper insert操作返回自增Id

Mybatis插入语句useGeneratedKeys="true"的用法

Mybatis插入语句useGeneratedKeys="true"的用法

mybatis插入出现org.apache.ibatis.executor.ExecutorException: No setter found for the keyProperty 'xx

springMVC+mybatis如何实现在A表中添加数据并把id同时添加到b表中

通过mybatis添加数据记录时,如何返回主键