实现插入数据后返回自增主键ID的几种方式(Several ways to return the self incrementing primary key ID after inserting data)

实现插入数据后返回自增主键ID的几种方式

在xml中 insert 标签中定义 :

* useGeneratedKeys为true,用来设置返回主键id的值,
* keyProperty 代表数据库记录主键字段

* keyColumn 代表 java对象成员属性名

在xml中 insert 标签中定义 :

* useGeneratedKeys为true,用来设置返回主键id的值,

* keyProperty 代表数据库记录主键字段

* keyColumn 代表 java对象成员属性名

1 xml 映射文件的方式

<!-- 插入数据:返回记录主键id值 --> <insert id="saveUser" useGeneratedKeys="true" keyProperty="id" keyColumn="id" parameterType="com.saiyou.entity.User">        insert into user(name,age) values (#{name},#{age}) </insert>

2 接口注解的方式

在接口映射器中通过注解@Options分别设置参数useGeneratedKeys,keyProperty,keyColumn值 如下

// 返回主键字段id值@Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")@Insert("insert into user(name,age) values (#{name},#{age})")void returnIdSaveUser(User user);

3 Mybatis Plus的方式

调用 BaseMapper 的 insert())或者调用service的save()方法后 ,默认将自增主键封装在 插入对象中

调用 BaseMapper 的 insert())或者调用service的save()方法后 ,默认将自增主键封装在 插入对象中

userMapper.insert(user);userService.save(user);

https://zhuanlan.zhihu.com/p/217375859

参考资料地址:

xml和@Param的方式,(参考资料显示此方式,不能返回自增的id),经验证,自增id是可以返回的

文档纠错:
————————

Several ways to return the self incrementing primary key ID after inserting data

Define in the insert tag in XML:
*Usegeneratedkeys is true, which is used to set the value of the returned primary key ID,
*Keyproperty represents the primary key field of the database record
*Keycolumn represents the member attribute name of the Java object

Define in the insert tag in XML:

*Usegeneratedkeys is true, which is used to set the value of the returned primary key ID,

*Keyproperty represents the primary key field of the database record

*Keycolumn represents the member attribute name of the Java object

1. How to map XML files

<!-- 插入数据:返回记录主键id值 --> <insert id="saveUser" useGeneratedKeys="true" keyProperty="id" keyColumn="id" parameterType="com.saiyou.entity.User">        insert into user(name,age) values (#{name},#{age}) </insert>

2 interface annotation mode

In the interface mapper, set the parameters usegeneratedkeys, keyproperty and keycolumn with the annotation @ options. The values are as follows

// 返回主键字段id值@Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")@Insert("insert into user(name,age) values (#{name},#{age})")void returnIdSaveUser(User user);

3 Mybatis Plus的方式

After calling the insert () method of basemapper or the save () method of service, the self incrementing primary key is encapsulated in the insert object by default

After calling the insert () method of basemapper or the save () method of service, the self incrementing primary key is encapsulated in the insert object by default

userMapper.insert(user);userService.save(user);

https://zhuanlan.zhihu.com/p/217375859

参考资料地址:

XML and @ param (the reference shows that this method cannot return the self incremented ID). After verification, the self incremented ID can be returned

文档纠错: