應用Java的MyBatis框架獲得MySQL中拔出記載時的自增主鍵。本站提示廣大學習愛好者:(應用Java的MyBatis框架獲得MySQL中拔出記載時的自增主鍵)文章只能為提供參考,不一定能成為您想要的結果。以下是應用Java的MyBatis框架獲得MySQL中拔出記載時的自增主鍵正文
第一步:
在Mybatis Mapper文件中添加屬性“useGeneratedKeys”和“keyProperty”,個中keyProperty是Java對象的屬性名!
<insert id="insert" parameterType="Spares"
useGeneratedKeys="true" keyProperty="id">
insert into spares(spares_id,spares_name,
spares_type_id,spares_spec)
values(#{id},#{name},#{typeId},#{spec})
</insert>
第二步:
Mybatis履行完拔出語句後,主動將自增加值賦值給對象Spares的屬性id。是以,可經由過程Spares對應的getter辦法獲得!
/**
* 新增備件
* @param spares
* @return
*/
@RequestMapping(value = "/insert")
@ResponseBody
public JsonResponse insert(Spares spares) {
int count = sparesService.insert(spares);
System.out.println("共拔出" + count + "筆記錄!"
+ "\n方才拔出記載的主鍵自增加值為:" + spares.getId());
另外一種辦法:
<insert id="insert" parameterType="Person">
<selectKey keyProperty="id" resultType="long">
select LAST_INSERT_ID()
</selectKey>
insert into person(name,pswd) values(#{name},#{pswd})
</insert>
拔出前實體id屬性為0;
拔出後實體id屬性為保留後自增的id;