Key Generation
Key Strategies
| Strategy | Usage on this datasource |
|---|---|
| Assigned | Supply the primary key before insertion. |
| Auto-increment | No numeric auto-increment key; native document IDs use the generation and return path described below. |
| 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. |
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:
- Method Annotations
- Mapper File
@Insert(value = "test.user_info.insertOne({name: #{name}})",
useGeneratedKeys = true, keyProperty = "id")
int insert(UserInfo item);
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
test.user_info.insertOne({name: #{name}})
</insert>
After mapper.insert(item), read item.getId(). These examples pass one entity argument, not an argument wrapped in @Param.
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.