实体类

@Data
public class TbUser implements Serializable {
    /**
     * 主键 数据库ID自增
     */
    @TableId(type = IdType.AUTO)
    private Integer id;
    //...
}

注意:在实体类主键字段上加注解@TableId(type = IdType.AUTO)否则会报错,参见https://blog.csdn.net/qq_40333952/article/details/115793996

xml

useGeneratedKeys:设置为true表示开启主键自增
keyProperty:指定数据库主键对应的实体类属性,将自增的主键赋值给传入的实体类参数

<insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="TbUser">
    INSERT INTO tb_user
    SET
    <if test="name!=null">
        name = #{name},
    </if>
    <if test="sex!=null">
        sex = #{sex},
    </if>
    <if test="tel!=null">
        tel = #{tel},
    </if>
    <if test="email!=null">
        email=#{email},
    </if>
    create_time = #{createTime}
</insert>

插入并获取自增主键值

//插入
userDao.insert(tbUser);
//tbUser.getId()获取到自增主键值
System.out.println(tbUser.getId());
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐