Skip to main content

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

StrategyUsage on this datasource
AssignedSupply the primary key before insertion.
Auto-incrementUse a database-generated numeric key.
UUIDUse UUID32 or UUID36 with a string key field.
SequenceNo sequence-key strategy on this datasource.
CustomUse 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;
@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
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.