Preface
It is common to insert a piece of data and return the ID. Mybatis is a little troublesome. Mybatis-plus may be just inserted before the API and then getId(). Here are two ways of Mybatis.
1. The first method
In the mapping file "*" in the entity class, write this:
<insert useGeneratedKeys="true" keyProperty="userId" parameterType=""> insert into user(userName,password,comment) values(#{userName},#{password},#{comment}) </insert>
Tips:
- useGeneratedKeys="true" means to set self-growth to the primary key
- keyProperty="userId" means assigning the incremental Id to the userId field in the entity class.
- parameterType="" This property points to the passed parameter entity class
- id="insertAndGetId" is not a fixed call, you can do it according to your own
Here is a reminder that there is no resultType attribute in the insert tag, so don't add it randomly.
The uerId in the entity class must have getter() and setter(); methods
When I created a table in MySQL database, I have already set up the field self-growth.
Second, the second method
1.Introduce the library
The code is as follows (example):
<!-- Insert a product --> <insert parameterType="" > <selectKey resultType="" order="AFTER" keyProperty="productId"> SELECT LAST_INSERT_ID() </selectKey> INSERT INTO t_product(productName,productDesrcible,merchantId)values(#{productName},#{productDesrcible},#{merchantId}); </insert>
Tips:
There is no resultType property in the <insert> tag, but there is a <selectKey> tag.
order="AFTER" means that the insert statement is executed first, and then the query statement is executed.
Can be set to BEFORE or AFTER.
If set to BEFORE, it will first select the primary key, set the keyProperty and then execute the insert statement.
If set to AFTER, then execute the insert statement first, and then the selectKey element - similar to the Oracle database, you can embed sequence calls in the insert statement
keyProperty="userId" means assigning the incremental Id to the userId field in the entity class.
SELECT LAST_INSERT_ID() means that the self-growth Id of the record that has just been inserted is queryed in MySQL syntax.
The uerId in the entity class must have getter() and setter(); methods
This is the article about the implementation of the newly added return id in mybatis. For more related content of the newly added return id in mybatis, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!