first step:
Add properties "useGeneratedKeys" and "keyProperty" in the Mybatis Mapper file, where keyProperty is the property name of the Java object!
<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>
Step 2:
After Mybatis executes the insert statement, it will automatically assign the self-increasing value to the property id of the object Spares. Therefore, it can be obtained through the getter method corresponding to Spares!
/** * New spare parts* @param spares * @return */ @RequestMapping(value = "/insert") @ResponseBody public JsonResponse insert(Spares spares) { int count = sparesService.insert(spares); System.out.println("Insert in total" + count + "Record!" + "/n The primary key self-growth value of the record just inserted is: " + spares.getId());
Another way:
<insert id="insert" parameterType="Person"> <selectKey keyProperty="id" resultType="long"> select LAST_INSERT_ID() </selectKey> insert into person(name,pswd) values(#{name},#{pswd}) </insert> The entity id attribute before insertion is 0;
The entity id attribute after insertion is the id that is automatically increased after saving;