欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

利用Java的MyBatis框架獲取MySQL中插入記錄時(shí)的自增主鍵

 更新時(shí)間:2016年06月01日 11:03:25   作者:hellostory  
這篇文章主要介紹了利用Java的MyBatis框架獲取MySQL中插入記錄的自增長字段值,其中大家可以看到MyBatis支持普通SQL語句所帶來的遍歷,需要的朋友可以參考下

第一步:
在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執(zhí)行完插入語句后,自動將自增長值賦值給對象Spares的屬性id。因此,可通過Spares對應(yīng)的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>

插入前實(shí)體id屬性為0;
插入后實(shí)體id屬性為保存后自增的id;

相關(guān)文章

最新評論