1. 程式人生 > >mapper.xml檔案中獲取最新插入資料的主鍵

mapper.xml檔案中獲取最新插入資料的主鍵

在開發過程中,我們常常用到在插入資料時,需要得到剛插入的資料的主鍵,MySQL中有以下做法: 1、推薦使用

<insert id="addVehicleParam" parameterType="com.corp.dto.VehicleParamAddDto" keyProperty="entity.paramId" useGeneratedKeys="true">
</insert>

keyProperty這個引數需要對應的是入參實體類的欄位,他會將這個主鍵直接對映到實體中,因此在獲取的時候需要使用實體的get方法來獲取:

int pk = paramAddDto.getParamId();

在這裡插入圖片描述 2、

<selectKey keyProperty="id" resultType="java.lang.Integer">
            SELECT LAST_INSERT_ID() AS id
</selectKey>

在這裡插入圖片描述