MyBatis --執行insert後獲取主鍵

最近作工程時遇到這種狀況,剛向數據庫插入一條記錄,立刻須要獲得該記錄的主鍵數據庫

網上搜索得出以下解決辦法app

<insert id="insert" parameterType="userInfo" useGeneratedKeys="true" keyProperty="id">
        insert into t_user(user_name,password) values(#{name},#{pswd})
    </insert>

實現層代碼以下code

        //先添加寵物信息
        CustomerPets customerPets = new CustomerPets();
        
        //customerPets設值
        customerPets.setCustomerId(userId);
        customerPets.setPetName(petName);
        customerPets.setSex(sex);
        customerPets.setPetCategoryId(petCategoryId);
        customerPets.setPetTypeId(petTypeId);
        customerPets.setBirthday(brithday);
        customerPets.setWeight(weight);
        customerPets.setUpdPid(PID);
        customerPets.setUpdUid(userId);
        customerPets.setUseFlag(Constant.UseFlag.USE.getFlag());
        customerPets.setAddUid(userId);
        customerPets.setAddPid(PID);
        
        int success =    customerPetsMapper.insertSelective(customerPets);
        
        if (success == 1) {
        //注意這裏取值
        String tmpPetId = customerPets.getPetId();
        }

備註:keyProperty後面的自增加主鍵,應該與t_user表中主鍵名稱保持一致。get

相關文章
相關標籤/搜索