mybatis-mysql 获得自增主键 Duplicate entry '1' for key 'PRIMARY' 错误

public void add(Goods goods) {
        Long goodsId = goodsMapper.insert(goods.getGoods());//获得主键
        goodsDesc.setGoodsId(goodsId);
        goodsDescMapper.insert(goodsDesc);   //主键作为desc的主键
    }
mapper.xml:
    

    SELECT LAST_INSERT_ID() AS id

insert into tb_goods (id, seller_id, goods_name, 
  default_item_id, audit_status, is_marketable, 
  brand_id, caption, category1_id, 
  category2_id, category3_id, small_pic, 
  price, type_template_id, is_enable_spec, 
        ....

报错:

Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'PRIMARY'

goods 的主键是 id(bigint)自增的

将上面的java文件改为,运行正常

    public void add(Goods goods) {
             goodsMapper.insert(goods.getGoods());
            goodsDesc.setGoodsId(goods.getId());
            goodsDescMapper.insert(goodsDesc);   //主键作为desc的主键
        }

原因:理解错误,goodsMapper.insert(goods.getGoods())返回的仍然是受影响的行,但是insert运行后,goods有了主键id的值.

你可能感兴趣的:(java,mybatis,mysql)