MyBatis Auto-Increment ID Setup
In MyBatis, there are several ways to set the id to auto increment.
- Using auto-increment fields in a database: by setting the id field in a database table to auto-increment (such as AUTO_INCREMENT), there is no need to manually set the id value in the MyBatis mapping file. When inserting data, the database will automatically generate and return the incremented id.
- Using database sequences: If the database supports sequences, a sequence can be created in the database, and then in the MyBatis mapping file, the next sequence value can be retrieved as an id using SELECT NEXTVAL(‘sequence_name’).
- Using UUID (Universally Unique Identifier): You can generate a unique id in MyBatis mapping files by using UUID, such as using SELECT UUID() to retrieve a UUID as an id.
Here is an example of using a database auto-increment field:
- Create an auto-increment field in the database table (for example, MySQL uses AUTO_INCREMENT).
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);
- Define the insert statement in the MyBatis mapping file without setting the id value.
<insert id="insertUser" parameterType="User">
INSERT INTO users (name) VALUES (#{name})
</insert>
- Insert data using MyBatis’s insert method in Java code.
User user = new User();
user.setName("John Doe");
userMapper.insertUser(user);
At this point, the database will automatically generate an incremented ID and assign it to the id property of the user object.