mybatis如何返回主键?
一:mysql数据库
使用useGeneratedKeys="true" 表示返回自动生成的主键,keyProperty="id"表示主键的属性是id,这里的id是实体类中的id
<insert id="saveStu" parameterType="stu" useGeneratedKeys="true" keyProperty="id">
insert into stu(
s_id,s_name,s_age
)
values(
#{id},
#{name},
#{age}
)
</insert>
s_id,s_name,s_age为表中的列
values中的参数的名字必须和实体类中的属性保持一致,使用的是实体类的get()方法。getName(),getAge()
二:oracle数据库
需要先查出主键的最大值,然后加一,再插入,如果使用的是序列,则需要先查出序列的值再插入
order:表示先生成id还是后生成id
<insert id="saveStu" parameterType="stu">
<selectKey resultType="int" keyProperty="id" order="BEFORE">
select etoakseq.nextVal from dual
</selectKey>
insert into stu(
s_id,s_name,s_age
)
values(
#{id},
#{name},
#{age}
)
</insert>

浙公网安备 33010602011771号