mysql 有结构如下的数据,之前操作插入了一些数据,然后删除了一些准备重新插入,但是插入的id每次都是按照最新的增长,而不是我想要个3,接下来456
直接设置增长起始值就好了呀
ALTER TABLE 你的表名 AUTO_INCREMENT = 3;
mapping映射文件的sql语句
<insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.wanmait.hospital.pojo.Doctor" useGeneratedKeys="true">
insert into doctor
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null">
`name`,
</if>
<if test="scope != null">
`scope`,
</if>
<if test="info != null">
info,
</if>
<if test="visible != null">
visible,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="scope != null">
#{scope,jdbcType=VARCHAR},
</if>
<if test="info != null">
#{info,jdbcType=VARCHAR},
</if>
<if test="visible != null">
#{visible,jdbcType=BIT},
</if>
</trim>
</insert>
返回的主键Id的获取方法
@Test
public void testInsert()
{
Doctor doctor = new Doctor();
doctor.setName("靳医生");
doctor.setInfo("66666一个字6");
doctorMapper.insertSelective(doctor);
System.out.println(doctor.getId());
}
本来就应该是这样,你想如下的场景:
假设你有两个表,班级表、学生表,学生表有一个外键关联给班级。
现在创建了一个班级,然后创建了几个学生。学生属于这个班级
然后删除了班级,再创建一个班级,如果id还是删除的那个,那这些学生岂不是莫名其妙关联给一个奇怪的班级了么?(明明删除的班级和再插入的根本不是一回事)
所以数据库就是这么设计的,删除的id被占坑了,新增加会跳过这个编号。这才合理。
如果你强行要这么做,你自己每次插入的时候取一个最大id值,再+1吧。