mybatis获取刚刚新插入数据的主键值 id

插入操作后,立马返回主键Id。查阅了很多资料,用keyProperty和useGeneratedKeys属性。useGeneratedKeys 参数只针对 insert 语句生效,默认为 false。当设置为 true 时,表示如果插入的表以自增列为主键,则允许 JDBC 支持自动生成主键,并可将自动生成的主键返回。

主要是以这样的方式:

<insert id="insertFileRecord" useGeneratedKeys="true" keyProperty="id">
      insert xxx
    </insert>

但是没有生效,于是我找用了useGeneratedKeys="true"的写法,发现我少写了

<insert id="insertFileRecord" parameterType="FileRecord" useGeneratedKeys="true" keyProperty="id">
      insert xxx
    </insert>

parameterType只能告诉它,在哪个实体类中,在Mybatis Mapper文件中添加属性 “useGeneratedKeys”和“keyProperty”,其中 keyProperty 是 Java 对象的属性名,而不是表的字段名。

但是还是没生效,我开始怀疑是我自增id是long类型,但实际上,并不是的,是我在mapper接口类中,加了这样一个注释

int insertFileRecord(@Param("fileRecord") FileRecord fileRecord);

并且在insert语句中fileRecord.fileName,去掉@Param,终于看到id了,

最后附上完整的写法:

mapper接口:

    /**
     * @Description: 新增数据
     * @Author: wj
     * @param: cc.jz.work.entity.FileRecord
     * @Return: 影响行数
     * @Date: 2022-03-31 10:37:18
     */
    int insertFileRecord(FileRecord fileRecord);

 xml:

<insert id="insertFileRecord" parameterType="cc.jz.work.entity.FileRecord"  useGeneratedKeys="true" keyProperty="id">
        insert into
        file_record
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="fileAddress != null and fileAddress != ''">
                file_address,
            </if>
            <if test="fileName != null and fileName != ''">
                file_name,
            </if>
            <if test="uploadUserId != null">
                upload_user_id,
            </if>
            <if test="uploadTime != null">
                upload_time,
            </if>
            <if test="status != null and status != ''">
                status,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="fileAddress != null and fileAddress != ''">
                #{fileAddress,jdbcType=VARCHAR},
            </if>
            <if test="fileName != null and fileName != ''">
                #{fileName,jdbcType=VARCHAR},
            </if>
            <if test="uploadUserId != null">
                #{uploadUserId,jdbcType=INTEGER},
            </if>
            <if test="uploadTime != null">
                #{uploadTime,jdbcType=TIMESTAMP},
            </if>
            <if test="status != null and status != ''">
                #{status,jdbcType=VARCHAR},
            </if>
        </trim>
    </insert>
 

猜你喜欢

转载自blog.csdn.net/heni6560/article/details/124194277