首页 > 技术文章 > mybatis如何成功插入后获取自增长的id

fsh1542115262 2014-07-09 19:55 原文

 

使用mybatis向数据库中插入一条记录,如何获取成功插入记录的自增长id呢?

需要向xml配置中加上一下两个配置:

<insert id="add" useGeneratedKeys="true" keyProperty="id" parameterType="com.work.model.ScheduleInfoTable">
    insert into scheduleInfo(title,content,time,state,userId) values(#{title},#{content},#{time},#{state},#{userId})
</insert>


其中keyProperty的值就是数据库中自增长字段名。

然后

public Object addSchedule(ScheduleInfoTable schedule){
        result.clear();
        if(service.addSchedule(schedule)){//插入记录到数据库,schedule中没有设置id的值
            result.put("success", true);
            result.put("msg", "日程记录添加成功");
            result.put("id", schedule.getId());//插入成功后,将自增长的id存入原来的model中,通过get方法就能拿到自增长的id了
            return result ;
        }

插入成功后,直接通过model的get方法就能获得自增长的id值

 

推荐阅读