last_insert_id()可用来获得最近insert的那行记录的自增字段值,注意,在高并发情况下,获取的到可能是其他表的自增记录的值,而非我们想要的表的自增记录的值。
与MyBatis整合的时候,使用selectKey来获取自增记录的值。
keyProperty:对应POJO的属性
order=‘AFTER’:在insert语句执行后,即在执行insert语句后执行select LAST_INSERT_ID(),如果order=‘BEFORE’则会获取前一条insert语句的自增主键的值。
<selectKey keyProperty="id" order="AFTER" resultType="long">
select LAST_INSERT_ID()
</selectKey>
<insert id="insert" parameterType="com.taotao.pojo.TbContentCategory" >
<selectKey keyProperty="id" order="AFTER" resultType="long">
select LAST_INSERT_ID()
</selectKey>
insert into tb_content_category (id, parent_id, name,
status, sort_order, is_parent,
created, updated)
values (#{id,jdbcType=BIGINT}, #{parentId,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR},
#{status,jdbcType=INTEGER}, #{sortOrder,jdbcType=INTEGER}, #{isParent,jdbcType=BIT},
#{created,jdbcType=TIMESTAMP}, #{updated,jdbcType=TIMESTAMP})
</insert>
对于mysql
insert into tb_content_category (id, parent_id, name, status, sort_order, is_parent, created, updated)
values (null,30,'测试','1','1',1,'2015-04-03 16:51:38','2015-04-03 16:51:38');
id为自增主键,当插入值为null的时候,id 还是自动增加
service只需在insert后面就可以拿到 自增的 id 的值
@Override
public TaotaoResult addContentCategory(long parentId, String name) {
TbContentCategory category = new TbContentCategory();
category.setParentId(parentId);
category.setName(name);
category.setSortOrder(1);
category.setStatus(1);
category.setIsParent(false);
Date date = new Date();
category.setCreated(date);
category.setUpdated(date);
tbContentCategoryMapper.insert(category);
//Mybatis通过select LAST_INSERT_ID(),获取自增ID
System.out.println(category.getId());
//判断父节点的isParetn是否为false,如果是false更新为true
TbContentCategory parentCategory = tbContentCategoryMapper.selectByPrimaryKey(parentId);
if(!parentCategory.getIsParent()){
parentCategory.setIsParent(true);
tbContentCategoryMapper.updateByPrimaryKey(parentCategory);
}
return TaotaoResult.ok(category);
}