後臺操作日誌,插入數據獲取的該數據主鍵ID為null
阿新 • • 發佈:2018-07-15
com sele ride model 不能 new t void sid sel
代碼如下:
@Override public void saveTopicResource(TopicResourceModel model, Integer userId) { TopicResource topicResource = new TopicResource(); BeanUtils.copyProperties(model, topicResource); int result=0; if (model.getResId() == null) { topicResource.setCreateUser(userId); result = topicResourceMapper.insertSelective(topicResource); model.setResId(topicResource.getResId()); if(result!=0){ logService.log("新增", SystemObject.TopicResource.getValue(), "新增的熱門主題ID為:" + model.getResId() + ",標題:" + model.getTopicName()); } } else { topicResource.setUpdateUser(userId); topicResource.setGmtUpdate(new Date()); result = topicResourceMapper.updateByPrimaryKeySelective(topicResource); if(result !=0){ logService.log("更新", SystemObject.TopicResource.getValue(), "更新後的熱門主題ID為:" + topicResource.getResId()); } } }
自己仔仔細細分析了一下插入數據邏輯,沒啥問題啊,就是獲取插入數據主鍵為null,然後查閱了一些資料
解決如下:首先需要把主鍵set進去,然後找到插入語句的SQL,添加兩個屬性
<insert id="insertSelective" parameterType="com.diyfintech.pojo.TopicResource" useGeneratedKeys="true" keyProperty="resId">
解釋一下啊:
useGeneratedKeys:默認值是false
設置是否使用JDBC的getGenereatedKeys方法獲取主鍵並賦值到keyProperty設置的領域模型屬性中。MySQL和SQLServer執行auto-generated key field,
因此當數據庫設置好自增長主鍵後,可通過JDBC的getGeneratedKeys方法獲取。但像Oralce等不支持auto-generated key field的數據庫就不能用這種方法獲取主鍵了
後臺操作日誌,插入數據獲取的該數據主鍵ID為null