Get the App
SLTechnology News&Howtos  ›  Database  › 

How to obtain the database self-generated primary key Id by MyBatis

Shulou Source: shulou.com Published: 2022-05-31 21:42:01 11月03日 Update

This article will explain in detail how MyBatis obtains the primary key Id generated by the database. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

MyBatis obtains the detailed explanation and example code of the self-generated primary key Id in the database

When using MySQL database, we usually use the self-increasing primary key of the database to generate the primary key automatically. If we need to insert data from the slave table when inserting the master table, we usually need to know the ID value of the primary key that is automatically generated when the master table is inserted.

The following describes how to obtain the primary key generated by the database at the same time when inserting with MyBatis:

1. XML configuration file

Insert into person (name,pswd) values (# {name}, # {pswd})

2. Methods in Mapper

Int insert (Person person)

Note that when this method is called, the int value returned is not the primary key, but the number of records inserted. The primary key id is assigned to the input person object and automatically assigned to the id property of the person object. For example:

Person person = new Person ("name", "psw"); / / num is the number of records inserted int num = PersonMapper.insert (person); / / the id property of the person object becomes the self-generated idint id = person.getId () This is the end of this article on "how to get the primary key Id generated by MyBatis". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

Tags: Data database autogenic object article at the same time properties methods more good practical code content examples files articles knowledge but reference help Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info macOS Linux NVidia MySQL