Skip to main content

Key Generation

Key Strategies

StrategyUsage on this datasource
AssignedSupply the primary key before insertion.
Auto-incrementNo numeric auto-increment key; native document IDs use the generation and return path described below.
UUIDUse UUID32 or UUID36 with a string key field.
SequenceNo sequence-key strategy on this datasource.
CustomUse a custom generator before or after insertion.

Use a Generated ID

If an inserted document omits _id, MongoDB's insert operation generates it. The adapter exposes the inserted ID for Mapper property assignment.

Provide a writable String id property on UserInfo. The following Mapper definitions fill it after insertion:

@Insert(value = "test.user_info.insertOne({name: #{name}})",
useGeneratedKeys = true, keyProperty = "id")
int insert(UserInfo item);

After mapper.insert(item), read item.getId(). These examples pass one entity argument, not an argument wrapped in @Param.

Note

The generated-key result column is _ID. To select it explicitly, set keyColumn = "_ID". Use _id when querying the primary-key field in a document.

Use an Assigned ID

An ObjectId and a string containing its hexadecimal text are different values. To query an existing ObjectId, wrap the bound text:

@Query("test.user_info.find({_id: ObjectId(#{id})})")
UserInfo findById(@Param("id") String id);

For Fluent conditions on an ObjectId field, map it with:

@Column(value = "_id", primary = true, whereValueTemplate = "ObjectId(?)")
private String id;

This wrapper is for ObjectId fields, not string _id values.

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.