錯誤示范
java代碼設置了@param參數,但是sql 字段沒有帶上參數,例如
void insertV2(@Param("historyDO") HistoryDO historyDO);
<insert id="insertDuplicate" parameterType="com.test.entity.HistoryDO"keyProperty="id" useGeneratedKeys="true">
keyProperty="id" 沒有對象參數,導致主鍵id插入成功后不能自動賦值
正確示范
方式一
insert語句使用了@Param參數,全程在設置參數需要帶上參數名稱,代碼如下
public interface HistoryMapper extends MyMapper<HistoryDO> {void insertV2(@Param("historyDO") HistoryDO historyDO);
}
<insert id="insertDuplicate" parameterType="com.test.entity.HistoryDO"keyProperty="historyDO.id" keyColumn="historyDO.id" useGeneratedKeys="true">INSERT INTO history (user_id,status,create_time,create_time_zone,update_time,update_time_zone)VALUES(#{historyDO.userId},#{historyDO.status},#{historyDO.createTime},#{historyDO.createTimeZone},#{historyDO.updateTime},#{historyDO.updateTimeZone})ON DUPLICATE KEY UPDATEstatus = VALUES(status),id = LAST_INSERT_ID(id),update_time = VALUES(update_time)</insert>
注意 keyProperty="historyDO.id" 需要加上參數對象名稱historyDO,
#{}參數也需要加上參數對象名稱historyDO
方式二
insert語句不使用@Param參數,全程在設置參數需不需要帶上參數名稱,代碼如下
public interface HistoryMapper extends MyMapper<HistoryDO> {void insertV2(HistoryDO historyDO);
}
<insert id="insertV2" useGeneratedKeys="true" keyProperty="id">INSERT INTO history (user_id,status,create_time,create_time_zone,update_time,update_time_zone)VALUES(#{userId},#{status},#{createTime},#{createTimeZone},#{updateTime},#{updateTimeZone})</insert>