Key Generation
MySQL generates primary keys with AUTO_INCREMENT; dbVisitor can assign the generated value to the entity after insertion.
Note
For general configuration, see Generated Keys.
Key Strategies
| Strategy | Usage on this datasource |
|---|---|
| Assigned | Supply the primary key before insertion. |
| Auto-increment | Use a database-generated numeric key. |
| UUID | Use UUID32 or UUID36 with a string key field. |
| Sequence | No sequence-key strategy on this datasource. |
| Custom | Use a custom generator before or after insertion. |
Using AUTO_INCREMENT
CREATE TABLE user_info (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(64)
) ENGINE=InnoDB;
- Builder API
- Method Annotations
- Mapper File
@Table("user_info")
public class UserInfo {
@Column(value = "id", primary = true, keyType = KeyType.Auto)
private Integer id;
@Column("name")
private String name;
}
UserInfo user = new UserInfo();
user.setName("mali");
LambdaTemplate lambda = ...;
lambda.insert(UserInfo.class).applyEntity(user).executeSumResult();
Integer id = user.getId(); // Auto-backfilled
Method Annotations
@Insert(value = "INSERT INTO user_info (name) VALUES (#{name})",
useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
int insertUser(UserInfo user);
Mapper File
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
INSERT INTO user_info (name) VALUES (#{name})
</insert>
Note
After inserting multiple entities, read each entity's ID; do not infer IDs from the first value. Rows skipped or updated by an insert-conflict strategy may not receive a generated ID.
Choosing the key source
For method annotations and Mapper files, use useGeneratedKeys with the default key source. The generated-key result is separate from the statement's ordinary result set; do not set generatedKeySource="resultSet" for these inserts.
The examples above show the supported generated-key path, including how to select the returned column with keyColumn.