MyBatis插入数据的时候,返回该记录的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代码如下:
(CountRateConfig countRateConfig) {int insertNum = Integer.parseInt(countRateConfigMapper.insert(countRateConfig) + “”);Long id = countRateConfig.getId();return insertNum;}
3、上述代码,如果插入数据成功的话,则可以找到数据库中对应的key;
结果是正确的,即可以读取正确的id。
像一颗深绿色的宝石镶嵌在云南大地上,