The MyBatis insert operation returns the id of the inserted record after inserting data
- 2021-07-10 19:59:08
- OfStack
When MyBatis inserts data, the id of the record is returned
<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>
First of all, we should ensure that the primary key Id of the database is self-increasing, and the other two attributes that need to be set are:
keyProperty="id"
useGeneratedKeys="true"
In this way, after inserting data, we can get the object after inserting data, and then get the id of the object through this object.
useGeneratedKeys=”true”
ID, which can obtain self-growth, only supports databases with self-growth mode (mysql, mssql, etc., but oracle does not support it)
Examples are as follows:
1. The configuration file of MyBatis is as shown in the previous pass;
2. The Java code used is as follows:
@Override
public int insert(CountRateConfig countRateConfig) {
int insertNum = Integer.parseInt(countRateConfigMapper.insert(countRateConfig) + "");
Long id = countRateConfig.getId();
return insertNum;
}
3. The above code, if the data is inserted successfully, the corresponding key in the database can be found;
The result is correct, that is, the correct id can be read.
Summarize