本文主要是介绍mybatis使用useGeneratedKeys+keyProperty返回自增主键,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在mybatis调用insert方法后,可以通过useGeneratedKeys+keyProperty属性获取自增主键。
用法如下:
实体类:这里的id为自增主键
public class Payment implements Serializable {private Long id;private String serial;
}
dao方法:
public int create(Payment payment);
dao方法对应的xml
<insert id="create" parameterType="Payment" useGeneratedKeys="true" keyProperty="id">insert into payment(serial) values(#{serial})</insert>
useGeneratedKeys :一个bool变量,为true时,返回数据库自动生成的记录主键id。
keyProperty:表明返回的主键名,在执行结束后相应的主键会被赋值,这里返回的主键为实体类中的主键id。
注意:返回的主键指在java程序中的形参,不会影响原先的sql执行结果,可以参考下面的代码。
每次在调用该接口后,会插入一个新的payment对象,并且获取生成的新的主键id。
@PostMapping("/payment/create")public CommonResult create( Payment payment){//执行create方法int result = paymentService.create(payment);log.info("****插入结果:"+result);if(result>0){log.info("插入成功,新增的用户id:"+payment.getId());return new CommonResult(200,"创建成功",result);}else {log.info("插入失败");return new CommonResult<>(444,"插入失败",null);}}
这篇关于mybatis使用useGeneratedKeys+keyProperty返回自增主键的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!