【mybatis】mybatis中insert操作,返回自增id

需求是这样的:

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

  

原本是这样的:

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

mapper.xml是这样的:

    <insert id="insertMaster" parameterType="java.lang.String" >
        ${masterInsertSql}
    </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字段接收 自增主键

就可以拿到insert操作后的自增主键了

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(指定字段) 去获取
原文地址:https://www.cnblogs.com/sxdcgaq8080/p/10869336.html