有的时候我们会有插入数据返回主键的需求 这个很简单 只需要两步操作
1.修改mapper.xml 在insert前面加一个标签 selectKey
order的意思是在增加表操作之后 resultType是操作表id的属性 一般是int long keyPropperty是主键的名称 一般是id
SELECT LAST_INSERT_ID() 表示查询最后一次增加的id
<insert id="insertSelective" parameterType="com.hangzhi.bean.Parent" >
<selectKey keyProperty="id" resultType="int" order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey>
insert into parent
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="phone != null" >
phone,
</if>
<if test="password != null" >
password,
</if>
<if test="name != null" >
name,
</if>
<if test="gender != null" >
gender,
</if>
<if test="email != null" >
email,
</if>
<if test="type != null" >
type,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="phone != null" >
#{phone,jdbcType=VARCHAR},
</if>
<if test="password != null" >
#{password,jdbcType=VARCHAR},
</if>
<if test="name != null" >
#{name,jdbcType=VARCHAR},
</if>
<if test="gender != null" >
#{gender,jdbcType=TINYINT},
</if>
<if test="email != null" >
#{email,jdbcType=VARCHAR},
</if>
<if test="type != null" >
#{type,jdbcType=TINYINT},
</if>
</trim>
</insert>
2. 我们就可以直接在java代码中获取这个id了 如下红色的部分, 就是在插入之后,用直接用对象的getId()获取就可以了.是不是很简单呢
public int addParent(Parent parent) {
parentMapper.insertSelective(parent);
int id = parent.getId();
System.out.println("添加的家长id="+id);
return id;
}