使用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值