MyBatis插入數據的時候,返回該記錄的id
<insert id="insert" keyProperty="id" useGeneratedKeys="true" parameterType="com.demo.domain.CountRateConfig"> insert into query_rate_config (code,partner_type,search_count, booking_count, ticket_count,rate_type) values (#{code,jdbcType=VARCHAR},#{partnerType,jdbcType=TINYINT}, #{searchCount,jdbcType=INTEGER}, #{bookingCount,jdbcType=INTEGER}, #{ticketCount,jdbcType=INTEGER},#{rateType,jdbcType=TINYINT}) </insert>
首先我們應該保證數據庫的主鍵Id是自增的,另外需要設置的兩個屬性為:
keyProperty="id"
useGeneratedKeys="true"
這樣的話,我們在插入數據之后,就可以得到插入數據之后的對象,然后通過該對象獲取該對象的id。
案例:
1、MyBatis的配置文件如上遍所示的一段代碼;
2、使用的Java代碼如下:
@Override public int insert(CountRateConfig countRateConfig) { int insertNum = Integer.parseInt(countRateConfigMapper.insert(countRateConfig) + ""); Long id = countRateConfig.getId(); return insertNum; }
3、上述代碼,如果插入數據成功的話,則可以找到數據庫中對應的key;
結果是正確的,即可以讀取正確的id。