利用Java的MyBatis框架获取MySQL中插入记录时的自增主键
第一步:
在MybatisMapper文件中添加属性“useGeneratedKeys”和“keyProperty”,其中keyProperty是Java对象的属性名!
<insertid="insert"parameterType="Spares"
useGeneratedKeys="true"keyProperty="id">
insertintospares(spares_id,spares_name,
spares_type_id,spares_spec)
values(#{id},#{name},#{typeId},#{spec})
</insert>
第二步:
Mybatis执行完插入语句后,自动将自增长值赋值给对象Spares的属性id。因此,可通过Spares对应的getter方法获取!
/**
*新增备件
*@paramspares
*@return
*/
@RequestMapping(value="/insert")
@ResponseBody
publicJsonResponseinsert(Sparesspares){
intcount=sparesService.insert(spares);
System.out.println("共插入"+count+"条记录!"
+"\n刚刚插入记录的主键自增长值为:"+spares.getId());
另一种方法:
<insertid="insert"parameterType="Person">
<selectKeykeyProperty="id"resultType="long">
selectLAST_INSERT_ID()
</selectKey>
insertintoperson(name,pswd)values(#{name},#{pswd})
</insert>
插入前实体id属性为0;
插入后实体id属性为保存后自增的id;