[java-ssm]向数据库新增数据后返回主键id

操作

需要在Mapper.xml文件中给insert标签内部第一行加上类似如下代码,表示新增完毕后立马查询id。
keyProperty属性填写的是你的实体类的主键字段;
order为after时表示是新增完后才返回主键id,如果是before则是新增前返回;
resultType是主键id类型。

<selectKey keyProperty="customerId" order="AFTER" resultType="java.lang.Long">
	SELECT LAST_INSERT_ID()
</selectKey>

如图

在这里插入图片描述
这个新增方法依旧是返回受影响行数(0或1)。而查询的id已经赋值到了参数里的对象中。
比如在业务层serviceImpl中可以输出新增后的对象的id。
因为数据库里该id是自增,所以新增前不需要填写id,该id原本是null。
在这里插入图片描述

输出结果

在这里插入图片描述
在这里插入图片描述
可以看到这个customers在新增前的id是null,但执行完新增方法后id就被赋值了。

注意事项

如果dao接口里给实体类对象起了注解名,如下的@Param(“customerPrice”)

/**
	 * 新增客户商品价格关系
	 * 
	 * @author huangzheshi
	 * @param customerPrice
	 * @return
	 */
int addCustomerPrice(@Param("customerPrice") SyCustomerPrice customerPrice);

那么在Mapper.xml里写selectKey标签时,keyProperty属性也必须用注解来指定字段(实体类对象注解名.字段名)。

错误写法如下
<insert id="addCustomerPrice">
	<selectKey keyProperty="cpId" order="AFTER" resultType="Long">
		SELECT LAST_INSERT_ID()
	</selectKey>
	INSERT INTO sy_customer_price
	VALUES(NULL,#{customerPrice.customerId},#{customerPrice.productId},#{customerPrice.customerPrice});
</insert>

这样不会报错,但始终是没法把返回的主键赋值进实体类对象中。

正确写法如下
<insert id="addCustomerPrice">
	<selectKey keyProperty="customerPrice.cpId" order="AFTER" resultType="Long">
		SELECT LAST_INSERT_ID()
	</selectKey>
	INSERT INTO sy_customer_price
	VALUES(NULL,#{customerPrice.customerId},#{customerPrice.productId},#{customerPrice.customerPrice});
</insert>

即把keyProperty="cpId"改成了keyProperty=“customerPrice.cpId”

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值