Skip to main content

Key Generation

Generate a business ID before insertion and read it from the entity afterward. The example below uses KeyType.UUID32.

Note

For general configuration, see Generated Keys.

Key Strategies

StrategyUsage on this datasource
AssignedAssigned IDs are accepted, but MergeTree does not enforce uniqueness; omitted IDs use column defaults.
Auto-incrementNo auto-increment generated keys.
UUIDUse UUID32 or UUID36 with a string key field.
SequenceNo sequence-key strategy on this datasource.
CustomGenerate IDs before insertion; after-insert callbacks cannot read auto-increment keys.

Key Strategies in Mapper Files

INSERT can bind an application-assigned ID directly. selectKey can run an additional query before or after insertion and fill its value into a parameter property. ClickHouse does not return JDBC generated keys; useGeneratedKeys cannot retrieve an auto-increment ID.

Using an Application-Side ID

CREATE TABLE event_log (id String, event_name String)
ENGINE = MergeTree ORDER BY id;

If the business requires a unique ID, generating it on the Java side is recommended — for example, UUID, Snowflake ID, or business numbers.

ClickHouse application-side ID mapping
@Table("event_log")
public class EventLog {
@Column(value = "id", primary = true, keyType = KeyType.UUID32)
private String id;

@Column("event_name")
private String eventName;
}
Lambda insert
EventLog event = new EventLog();
event.setEventName("login");

LambdaTemplate lambda = ...;
lambda.insert(EventLog.class)
.applyEntity(event)
.executeSumResult();

String id = event.getId();

KeyType.UUID32 / KeyType.UUID36 generates IDs before insert and does not depend on ClickHouse returning generated keys.

For inserting several events at once, see Batch Inserts.

Assigned IDs

With KeyType.None, dbVisitor uses the ID already assigned to the entity. A MergeTree sorting key does not reject duplicate IDs. Omitting the ID column uses its default value:

CREATE TABLE manual_keys (id Int32, name String)
ENGINE = MergeTree ORDER BY id;

INSERT INTO manual_keys (id, name) VALUES (1001, 'first'), (1001, 'second');
INSERT INTO manual_keys (name) VALUES ('without ID');

The first two rows both have ID 1001; the third has ID 0. If IDs must be present and unique, generate and validate them before writing rather than relying on duplicate-key exceptions.

Custom Key Generators

For example, a beforeApply handler can generate an order number, assign it to the entity, and include it in the INSERT. The handler can access the current connection and mapping information. An afterApply callback can run post-insert logic, but ClickHouse does not return identity-generated keys to read back.

See Key Generators for configuration.