Home  >  Q&A  >  body text

java - How to obtain the newly added id in mybatis

<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 layer
public int saveCustomer(CustomerEntity cs);
This method always returns 1. The value of object.id is always empty. The database is 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());
天蓬老师天蓬老师2667 days ago1105

reply all(6)I'll reply

  • 伊谢尔伦

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

    @福生百记 Add useGeneratedKeys="true"

    on its basis

    reply
    0
  • 欧阳克

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

    What this method returns is actually the number of records affected.
    You can directly get the ID of the entity class after inserting.

    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());

    reply
    0
  • 淡淡烟草味

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

    Can we take a look at the entity class?

    reply
    0
  • 仅有的幸福

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

    useGeneratedKeys="true" keyProperty="id" In the xml configuration, keyProperty is the primary key. Check whether your data number is set with id as the primary key and the period as auto-increment. If so, after the insert is executed, the value of the primary key will be reflected to In the primary key of your entity class

    reply
    0
  • 扔个三星炸死你

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

    <insert id="save" parameterType="atyy.model.ArticleCategoryPO" useGeneratedKeys="true">
    </insert>
    Just add an attribute useGeneratedKeys="true"

    reply
    0
  • 为情所困

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

    1. The database id must be auto_increment
    2. Configure useGeneratedKeys="true" and keyProoerty
    3. The value you get by calling the mapper interface method, that is, the total 1 you get is the number of records affected. If you want to get the object id, please click and use the corresponding getter method

    reply
    0
  • Cancelreply