我正在探索我的 RDBMS 世界并进入 MongoDB 的神秘海洋。我正在使用 Spring Data 来帮助我进行冒险。我需要在两个集合中的文档之间创建手动引用(我读过 DBRefs 很昂贵),我的 pojo 是这样的:
public class User {
@Id
private String id;
private String name;
private String password;
...
}
public class Game {
@Id
private String id;
private String name;
private String platform;
private String userID;
...
}
userID 是现有用户的 id,它作为 ObjectId 存储在数据库中。当我检索游戏文档时,userID 字段正确映射到字符串值,但我希望 spring-data 在持久化时进行反向映射(字符串到 ObjectId),我不知道该怎么做。
请有人指出我正确的方向吗? 我是否应该放弃这种方法并采用将这个字段直接存储为字符串的简单解决方案?
非常感谢!
最佳答案
默认使用spring-data-mongodb时,Spring使用一个MappingMongoConverter
将域对象转换为|来自文档。
id 属性的默认转换器策略如下:
The following outlines what field will be mapped to the '_id' document field:
A field annotated with @Id (org.springframework.data.annotation.Id) will be mapped to the '_id' field. A field without an annotation but named id will be mapped to the '_id' field. The following outlines what type conversion, if any, will be done on the property mapped to the _id document field.
If a field named 'id' is declared as a String or BigInteger in the Java class it will be converted to and stored as an ObjectId if possible. ObjectId as a field type is also valid.
默认情况下,不会对任何其他标准属性进行此转换。因此,如果您希望 userID
字段保存为 ObjectId
只需更改字段类型:private ObjectId userID;
如果您想将 User
的 id
属性保存为 MongoDB 中的字符串,并不是说相反的情况不那么简单,您必须提供自己的映射转换器覆盖 writeInternal
方法(顾名思义,它暗示你不应该)或在转换过程中进一步覆盖其他一些 Spring MongoDB 管道 bean
关于java - 将 ObjectId 字段正确映射到 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21708917/