今天在做项目的时候需要用到上次数据更新或者插入的id,学习了一下找到此方法,记录一下。
在MyBatis中,当插入一条新数据后,可以使用useGeneratedKeys属性和keyProperty属性来获取新插入数据的ID。useGeneratedKeys属性告诉MyBatis使用JDBC的getGeneratedKeys方法来获取数据库生成的主键,keyProperty属性则指定哪个Java对象的属性应该被设置为这个主键。
在xml中在做更新操作时,加入useGeneratedKeys属性和keyProperty属性,或者上次更新数据的id。
<update id="updateStationManagerInfo" useGeneratedKeys="true" keyProperty="id">
update storage_tool_station_info_confirm
set team_manager_id = #{teamManagerId},
team_manager_face = #{teamManagerFace},
team_manager_confirm_time = SYSDATE(),
station_account_id = #{stationAccountId},
station_face = #{stationFace},
station_confirm_time = SYSDATE(),
type = #{type}
where id = #{id}
</update>
在xml中在做插入操作时,加入useGeneratedKeys属性和keyProperty属性 ,获取上次插入数据的id
<insert id="insertStationManagerInfo" useGeneratedKeys="true" keyProperty="id">
INSERT INTO storage_tool_station_info_confirm(model_id, team_id, team_manager_id, team_manager_face,
team_manager_confirm_time, station_account_id, station_face,
station_confirm_time,
tool_count, operate_time, receiptor, type)
VALUES (#{modelId}, #{teamId}, #{teamManagerId}, #{teamManagerFace}, #{teamManagerConfirmTime},
#{stationAccountId}, #{stationFace}, #{stationConfirmTime}, #{recipentCount}, #{operateTime},
#{receiptor}, #{type});
</insert>
java代码里取出就可以了
例如:
//更新操作
warehouseRequisitionMapper.updateStationManagerInfo(toolInfoConfirm);
//取id
log.info("id-------------:"+toolInfoConfirm.getId());
插入数据
//取id
log.info("Insert StorageToolInfoConfirm successfully.");
log.info("id-------------:"+toolInfoConfirm.getId());
注意:在使用此方式取id时,需要保证数据库表的id是自增的。