Mybatis新增数据返回自增主键

一、数据库设计

选择主键自动递增
image

二、Mybatis配置

设置eyProperty="id" useGeneratedKeys="true"

<insert id="insertSentence" keyProperty="id" useGeneratedKeys="true">
       sql脚本
</insert>

三、获取返回值

xxxDao.insertSentence(entity);
//通过实体类的getId()方法获取新增数据的主键id
int id = entity.getId();

四、易错问题

keyProperty="id"设置好之后,方法报错提示“id not found” ?
原因:在dao层给新增方法的实体类起了别名,导致mybatis识别不到主键ID,如图
image
解决方法:

1、keyProperty="sentence.id" #换上别名
2、不用别名...
posted @ 2022-08-15 14:14  棒棒糖堂堂主  阅读(348)  评论(0)    收藏  举报