一、需求
在数据库种类似id这样的主键值都是自动增长的。但是如果有这样的需求时:插入一条记录后,自动生成了主键,而这个主键需要在其他表中使用时。此时需要获取这个自动增长的id值是什么!
1、编写接口
/**
* 插入Car信息,并且使用生成的主键值
* @param car
* @return
*/
int insertCarUseGeneratedKeys(Car car);
2、编写mapper配置文件
useGeneratedKeys=“true” 表示使用自动生成的主键值
keyProperty=“id” 表示把生成的主键值放到对象对应的哪个属性上。这个表示赋值给Car对象的id属性上
<insert id="insertCarUseGeneratedKeys" useGeneratedKeys="true" keyProperty="id">
insert into t_car
values(null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType})
</insert>
3、测试程序
@Test
public void testGeneratedKeys() throws IOException {
SqlSession session = SqlSessionUtil.openSession();
CarMapper mapper = session.getMapper(CarMapper.class);
Car car = new Car(null,"0930","陈川",30.0,"2022-20-26","小汽车");
int count = mapper.insertCarUseGeneratedKeys(car);
session.commit();
session.close();
System.out.println(car);
}