一、背景
有的時候需要返回插入值後DB自動增長生成的記錄ID,在Mybatis的 環境下如何做呢?
二、代碼示例
<insert id="insert" parameterType="com.qunar.fax.model.qunar.entry.FaxSendNotify" useGeneratedKeys="true" keyProperty="id"> <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id"> SELECT LAST_INSERT_ID() AS ID </selectKey> INSERT INTO fax_send_notify( header_action, taskId, tel_number, send_datetime, duration, fax_status, remote_id, error_msg, connect_speed, file_size, pages, status, send_pages, create_time, callback_time, retry_count, source, version ) VALUE( #{headerAction}, #{taskId}, #{telNumber}, #{sendDatetime}, #{duration}, #{faxStatus}, #{remoteId}, #{errorMsg}, #{connectSpeed}, #{fileSize}, #{pages}, #{status}, #{sendPages}, #{createTime}, #{callBackTime}, #{retryCount}, #{source}, #{version} ) </insert>
運行之後,能夠自動將ID賦值到對象FaxSendNotify的id屬性裏面,so easy!
補充一句,這是Mysql db下的示例