DATAMONGO-1798 - Introduce @MongoId annotation for fine grained id conversion control.
@MongoId allows more fine grained control over id conversion by specifying the intended id target type. This allows to skip the automatic to ObjectId conversion of values that happen to be valid ObjectId hex strings.
public class PlainStringId {
@MongoId String id; // treated as String no matter what
}
public class PlainObjectId {
@MongoId ObjectId id; // treated as ObjectId
}
public class StringToObjectId {
@MongoId(FieldType.OBJECT_ID) String id; // treated as ObjectId if the value is a valid ObjectId hex string
}
Original pull request: #617.
This commit is contained in:
committed by
Mark Paluch
parent
75b6dc7a0e
commit
5d39191f0b
@@ -669,6 +669,31 @@ If no field or property specified in the previous sets of rules is present in th
|
||||
|
||||
When querying and updating, `MongoTemplate` uses the converter that corresponds to the preceding rules for saving documents so that field names and types used in your queries can match what is in your domain classes.
|
||||
|
||||
Some environments however require a different approach to mapping `Id` values. Maybe data has feed to mongodb not running throught the Spring Data mapping layer, an thus containing plain `String` values as `id` that represent a valid `ObjectId`.
|
||||
Reading documents from the store back to the domain type works just fine but querying for documents via their `id` is cumbersome due to the `ObjectId` conversion. Therefore documents cannot be retrieved that way.
|
||||
For those cases `@MongoId` provides more control over the actual id mapping attempts.
|
||||
|
||||
.`@MongoId` mapping
|
||||
====
|
||||
[source,java]
|
||||
----
|
||||
public class PlainStringId {
|
||||
@MongoId String id; <1>
|
||||
}
|
||||
|
||||
public class PlainObjectId {
|
||||
@MongoId ObjectId id; <2>
|
||||
}
|
||||
|
||||
public class StringToObjectId {
|
||||
@MongoId(ObjectId.class) String id; <3>
|
||||
}
|
||||
----
|
||||
<1> The id is treated as `String` no matter what.
|
||||
<2> The id is treated as `ObjectId`.
|
||||
<3> The id is treated as `ObjectId` if the given `String` is a valid ObjectId hex, otherwise as String.
|
||||
====
|
||||
|
||||
[[mongo-template.type-mapping]]
|
||||
=== Type Mapping
|
||||
|
||||
|
||||
Reference in New Issue
Block a user