Mybatis在 insert 之后想获取自增的主键 id,但却总是返回1

今早写了这个代码

想要想获取插入后的主键值,测试时却一直返回1,在网上搜了2小时,一直以为是自己写错了.....直到我看到这篇文章https://www.cnblogs.com/quan-coder/p/8728410.html

确实被自己蠢哭了

dao的代码没什么问题,是理解上有偏差

1. 想要获取自增主键img_id,应该通过对象的getImgId()方法,而并不是insert的返回值,insert的返回值表示的是影响行数

 我一开始一直以为是insert之后返回的是主键的Id,其实不是这样的,

比如我的这个方法  public int insertImg(Img img)

添加了@options(useGeneratedKeys = true ......省略)之后

mybatis 会在查询之后,把主键id封装进原对象 img 里面,而不是将 img_id 值返回,想获取 img_id 的值,直接 img.getImgId()就可以了

以下是测试代码,供理解参考,可根据自己的实际情况进行修改

 

package com.mall.conf;

import org.apache.ibatis.annotations.Options;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.spring.boot.test.autoconfigure.MybatisTest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.mall.bean.Img;
import com.mall.dao.ImgDao;


@RunWith(SpringRunner.class)
// 这块需要引入依赖 mybatis的测试依赖jar
@MybatisTest
// 这个注解的意义是指定了默认数据源
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@SpringBootTest
public class ImgDaoTest {

	@Autowired
	ImgDao imgDao;
	
	@SuppressWarnings("deprecation")
	@Test
	public void insertImg() {
		Img img =  new Img();
		img.setUrl("/img/img.jpg");
		
		/*
		 * 这是我原本错误的理解,以为会返回主键id,这是错的
		 * 它只会返回影响行数
		 */
		int id = imgDao.insertImg(img);
		Logger log = LoggerFactory.getLogger(getClass());
		log.info("" + id);
		
		/*
		 * 这才是正确的,insert通过 img.getImgId() 来获取主键的值
		 */
		imgDao.insertImg(img);
		Logger log = LoggerFactory.getLogger(getClass());
		log.info("" + img.getImgId());
		
		/*
		 * 如果你还不放心的话,
		 * 可以试着把dao里面的@options注解那一行注释掉
		 * 然后运行以下代码,你会发现,输出null,主键值没有被封装到对象里面,
		 *这就是加不加 @Options(useGeneratedKeys= ture)的区别
		 */
		imgDao.insertImg(img);
		Logger log = LoggerFactory.getLogger(getClass());
		log.info("" + img.getImgId());
		
		
	}
}

返回影响行数

直接用对象调用getid方法获取id值

没有用@Options注解,原对象取不到 id 值

 

 

 

 

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值