第一步:
在Mybatis Mapper文件中添加属性“useGeneratedKeys”和“keyProperty”,其中keyProperty是Java对象的属性名!
1
2
3
4
5
6
|
< insert id = "insert" parameterType = "Spares" useGeneratedKeys = "true" keyProperty = "id" > insert into spares(spares_id,spares_name, spares_type_id,spares_spec) values(#{id},#{name},#{typeId},#{spec}) </ insert > |
第二步:
Mybatis执行完插入语句后,自动将自增长值赋值给对象Spares的属性id。因此,可通过Spares对应的getter方法获取!
1
2
3
4
5
6
7
8
9
10
11
12
|
/** * 新增备件 * @param spares * @return */ @RequestMapping (value = "/insert" ) @ResponseBody public JsonResponse insert(Spares spares) { int count = sparesService.insert(spares); System.out.println( "共插入" + count + "条记录!" |
另一种方法:
1
2
3
4
5
6
|
< insert id = "insert" parameterType = "Person" > < selectKey keyProperty = "id" resultType = "long" > select LAST_INSERT_ID() </ selectKey > insert into person(name,pswd) values(#{name},#{pswd}) </ insert > |
插入前实体id属性为0;
插入后实体id属性为保存后自增的id;