搜尋

首頁  >  問答  >  主體

java - mybatis如何實作取得新增得id

<insert id="saveCustomer" parameterType="com.xiaonatech.dsx.entity.CustomerEntity" useGeneratedKeys="true" keyProperty="policyID">

        insert into customer                 (certType,code,password,name,mobile,effDate,expDate,address,createID,createTime,updateID,updateTime) 
        values
             (#{certType},#{code}, #{password}, #{name}, #{mobile},  #{effDate},#{expDate},#{address},#{createID},#{createTime} ,#{updateID},#{updateTime})
</insert>

dao層
public int saveCustomer(CustomerEntity cs);
這個方法回傳得一直是1。物件.id得值 一直是空。資料庫是mysql
CustomerEntity applyRecord = new CustomerEntity();

    applyRecord.setCertType("0");
    applyRecord.setCode("423565462256");
    applyRecord.setPassword("123456");
    applyRecord.setName("sds");
    applyRecord.setMobile("12345678978");
    applyRecord.setCreateID("150");
    applyRecord.setUpdateID("150");
    applyRecord.setUpdateTime(new Date());
    int i = dao.saveCustomer(cs);
    System.out.println("i========="+i+"  id================"+applyRecord.getCarOwnerID());
天蓬老师天蓬老师2809 天前1244

全部回覆(6)我來回復

  • 伊谢尔伦

    伊谢尔伦2017-06-30 09:55:48

    @浮生百記 在其基礎上加上useGeneratedKeys="true"

    回覆
    0
  • 欧阳克

    欧阳克2017-06-30 09:55:48

    這個方法回傳的實際上是影響的記錄數。
    你insert之後直接去拿實體類別的id即可。

    ApplyRecord applyRecord = new ApplyRecord();
    applyRecord.setAccount("1234");
    applyRecord.setCode("123");
    Timestamp now = new Timestamp(System.currentTimeMillis());
    applyRecord.setGmtCreate(now);
    applyRecord.setGmtModified(now);
    int i = applyRecordDao.insert(applyRecord);
    logger.info("{}",applyRecord.getId());

    回覆
    0
  • 淡淡烟草味

    淡淡烟草味2017-06-30 09:55:48

    實體類別可以看下麼

    回覆
    0
  • 仅有的幸福

    仅有的幸福2017-06-30 09:55:48

    useGeneratedKeys="true" keyProperty="id" xml配置中keyProperty為主鍵你看你的資料數是不是設id為主鍵並設定期為自增,如果設定執行完insert後,主鍵的值就會反射到你實體類別的主鍵中

    回覆
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-06-30 09:55:48



    加入一個屬性就行了useGeneratedKeys="true"

    回覆
    0
  • 为情所困

    为情所困2017-06-30 09:55:48

    1.資料庫id必須是auto_increment
    2.配置useGeneratedKeys="true"以及keyProoerty
    3.你呼叫mapper介面的方法得到的數值,也就是總拿到的1是影響的記錄數,要想拿到對象的id,請點選對應的getter方法

    回覆
    0
  • 取消回覆