mysql select LAST_INSERT_ID()

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);
	}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值