Select primary key (ID) from Mybatis;

Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

When I was thinking about what to write, I saw this question on a basic interview question and wrote it down.

👨💻 interviewer: Mybatis can return primary key ID after insert statement? If so, can you make it happen?

🙋 I: of course it is possible, even JDBC can do things, Mybatis can also do.

Start typing code…

1.1. Set the ID increment of the Mysql database

 <insert id="insertUser" parameterType="com.crush.mybatisplus.entity.User">
     INSERT  INTO tb_user (username,password) VALUES(#{username},#{password});
     <selectKey resultType="java.lang.Long" order="AFTER" keyProperty="id">
         SELECT LAST_INSERT_ID()
     </selectKey>
 </insert>
Copy the code

Explanation:

  1. Mysql primary key incrementSELECT LAST_INSERT_ID()The last ID value is returned.
  2. The argument passed must be an object, not a single argument such as String int
  3. orderProperty, value rangeBEFORE|AFTERTo specify whether to execute before or after the INSERT statementselectKeyOperation.AFTERGenerally used when Mysql increment,BEFOREGenerally used to obtain a custom ID.
  4. keyPropertyProperty, the default valueunset, for settinggetGeneratedKeysMethod orselectKeyWhich attribute in the domain model will the child element return value be assigned to, i.e. the primary key ID of the corresponding database in your entity class.
  5. Finally, in the entity class, there should be primary key get and set methodsimpllayercontrollerGetId () can obtain the primary key ID after this insertion, and return to the front end.

Such as:

 @Override
 public Long insert(User user) {
     return  userMapper.insertUser(user)>0? user.getId():null;
 }
Copy the code

1.2. Use UUID to add the primary key automatically

 <insert id="insertUser2" parameterType="com.crush.mybatisplus.entity.User">
     <selectKey keyProperty="id" order="BEFORE" resultType="String">
         select uuid()
     </selectKey>
     INSERT INTO tb_user (id,username,password) VALUES(#{id},#{username},#{password});
 </insert>
Copy the code

The result is the same as above.

Mybatis -plus returns a custom ID after an insert statement

👨💻 interviewer: Can you use Mybatis-Plus? How does Mybatis-Plus do this? Is there an easy way?

🙋 I: still studious, just can answer this question.

Step by step:

You can use Mybatis-Plus’s savA method directly, or mapper’s Insert method, which will automatically populate the result into your mapped entity class. So you can access your data directly.

 @PostMapping("/add3")
 public Object add3(@RequestBody User user){
     return tbUserService.save(user)==true? user.getId():"Insert failed";
 }
Copy the code

We can also print the User directly to see:

 @PostMapping("/add3")
 public Object add3(@RequestBody User user){
     tbUserService.save(user);
     System.out.println("User after insert:"+user);
     return user.getId();
 }
Copy the code
User after insert: User(ID =890909294458048512, USERNAME =123456, password=123456, deleted=0, createTime=2021-09-24T10:35:36.873908700, UpdateTime = 2021-09-24 T10:35:36. 873908700)Copy the code

You can also use the annotation method, but the annotation kind is to move the second method in Mybatis above to the annotation.

 @Insert(value = "INSERT INTO t_XXXX" + "XXX,XXX,XXX " + "VALUES (XXX,XXX,XXX)")
 @SelectKey(statement="select LAST_INSERT_ID()",keyProperty = "id",before = false,resultType = Long.class)
 Integer testInsert1(MessageMould messageMould);
Copy the code

Three, talk to yourself

This article is a simple introduction, specific use of specific circumstances specific analysis.

Hello, THIS is blogger Ning Zaichun: homepage

I hope you found this article useful!!

Wish us: by the time we meet on another day, we have achieved something.