How is the insert tag used in MyBatis?
MyBatis’ insert tag is used to execute database insert operations. It can be used in mapping files and has several different ways of usage.
- Single insertion:
In this example, insertUser is the id for the insertion operation, parameterType specifies the type of parameters being passed in, and name and age are properties of the User object.
- Batch insert:
INSERT INTO user(name, age) VALUES
(#{user.name}, #{user.age})
In this example, insertUsers is the ID for batch insertion operation, parameterType specifies the type of parameters passed in as List, list is the parameter name passed in, and item specifies the name of the object for each loop.
- Get the automatically generated primary key value after insertion:
INSERT INTO user(name, age) VALUES (#{name}, #{age})
In this example, setting useGeneratedKeys to true means using the primary key value generated by the database, and keyProperty specifies that the automatically generated primary key value is set to the id property of the User object.
- Retrieve the auto-generated primary key value after insertion:
In this example, the keyColumn specifies the name of the auto-increment primary key column in the database. MyBatis will set the auto-increment primary key value to the id attribute of the User object.
These are some common uses of the insert tag in MyBatis. Depending on specific requirements, you can choose the appropriate method to execute the insertion operation.