用insert into 插入数据后直接返回刚插入数据的ID (自增ID)

需求是这样的:

mybatis中insert操作,返回自增id,因为这个自增id需要给后续业务用到

原本是这样的

将insert语句传入,正常执行insert操作,返回int永远是 0[失败] 或者 1[成功]

在pg数据库中,可以直接这样写

在插入插入语句后,直接加上RETURNING ID

在mybatis中

mapper.xml是这样的:

<insert id="insertMaster" parameterType="java.lang.String" >

${masterInsertSql}

不用加 RETURNING ID

</insert>

mapper.java是这样的:

int insertMaster(@Param("masterInsertSql") String masterInsertSql); 

想要实现mybatis的insert操作返回自增id,需要这样:

1.首先,你需要一个Bean

这个Bean对象作为参数传入,这个bean需要一个字段接收自增id

所以,我得创建一个对象:

public class WorksheetMasterSQLBean {

private Long id;

private String masterInsertSql;

}

 

这个对象就多了一个id,用来接收自增id。

把原本的参数,放在这个对象中。

2.我需要将这个对象作为入参传递给mybatis

所以,我的mapper.java这样写:

int insertMaster(WorksheetMasterSQLBean masterBean);

 

3.最后,我需要指定我传入的对象,哪个字段用来接收insert之后返回的自增id

所以,我的mapper.xml需要这样写

<insert id="insertMaster" parameterType="com.lqjava.daywork.api.beans.WorksheetMasterSQLBean" useGeneratedKeys="true" keyProperty="id">

${masterInsertSql}

</insert>

useGeneratedKeys="true"

keyProperty="id" //指定bean中的id字段接收 自增主键

 4.最终要的,在java中调用时候,怎么拿到自增主键?

错误拿取:

int i = tableDataMapper.insertMaster(masterSQL);

System.out.println("主键:"+i); //返回的依旧是 0 或者 1 ,代表执行成功或失败

 正确拿取:

tableDataMapper.insertMaster(masterSQL);

System.out.println("主键:"+masterSQL.getId());

//因为上面说了,mybatis会把自增id封装在你的入参bean的指定字段中,所以应该从 入参.get(指定字段) 去获取

 


版权声明:本文为li15974168626原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。