操作
需要在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”