记得老早就做过这种功能,就是在新增的时候返回主键id,但最近碰到又是折腾了很久,真是年纪大了,越简单的越记不住了,话不多说,上代码
- mapper文件代码
<insert id="insert" parameterType="com.lm.jsyst.entity.Simulation" useGeneratedKeys="true" keyProperty="id">
INSERT INTO exam
(user_id, total_num, correct_num, error_num, create_time)
VALUES
(#{userId}, #{totalNum}, #{correctNum}, #{errorNum}, #{createTime})
</insert>
- java代码
examService.create(exam);
Long id = exam.getId();
总结:重点在于xml的insert需要配置useGeneratedKeys=“true” keyProperty="id"这两个属性,然后java对象通过getId()获取该主键值。