java - mybatis如何實現(xiàn)獲取新增得id
問題描述
<insert 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得值 一直是空。數(shù)據(jù)庫是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());
問題解答
回答1:@浮生百記 在其基礎(chǔ)上加上useGeneratedKeys='true'
回答2:這個方法返回的實際是影響的記錄數(shù)。你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());回答3:
實體類可以看下么
回答4:useGeneratedKeys='true' keyProperty='id' xml配置中keyProperty為主鍵 你看你的數(shù)據(jù)數(shù)是不是設(shè)id為主鍵并設(shè)置期為自增,如果設(shè)置執(zhí)行完insert后,主鍵的值就會反射到你實體類的主鍵中
回答5:<insert parameterType='atyy.model.ArticleCategoryPO' useGeneratedKeys='true'></insert>加入一個屬性就行了useGeneratedKeys='true'
回答6:1.數(shù)據(jù)庫id必須是auto_increment2.配置useGeneratedKeys='true'以及keyProoerty3.你調(diào)用mapper接口的方法得到的數(shù)值,也就是總拿到的1是影響的記錄數(shù),要想拿到對象的id,請點用對應(yīng)的getter方法
相關(guān)文章:
1. mac OSX10.12.4 (16E195)下Mysql 5.7.18找不到配置文件my.cnf2. mysql - 怎么生成這個sql表?3. mysql儲存json錯誤4. php - 公眾號文章底部的小程序二維碼如何統(tǒng)計?5. mysql - 表名稱前綴到底有啥用?6. mysql - 數(shù)據(jù)庫表中,兩個表互為外鍵參考如何解決7. Navicat for mysql 中以json格式儲存的數(shù)據(jù)存在大量反斜杠,如何去除?8. 在mybatis使用mysql的ON DUPLICATE KEY UPDATE語法實現(xiàn)存在即更新應(yīng)該使用哪個標(biāo)簽?9. mysql - 數(shù)據(jù)庫建字段,默認(rèn)值空和empty string有什么區(qū)別 11010. sql語句 - 如何在mysql中批量添加用戶?
