这是我的MongoDb结构,
This is my MongoDb structure,
db.user.find();用户:
{ "name" : "KSK", "claim" : [objectId("52ffc4a5d85242602e000000"),objectId("52ffc4a5d85242602e000001")] }声明:
[ { "_id" : "52ffc4a5d85242602e000001", "claimName" :"XXXX" }, { "_id" : "52ffc4a5d85242602e000000", "claimName" :"YYY" } ]我的实体类是:
@Document(collection="user") public class User{ @Id private String id; private String name; @DBRef private List<Claim> claim; // setter and getter }索赔班:
@Document(collection="Claim") public class Claim{ @Id private String id; private String claimName; }我有一种通过如下名称来获取用户的方法,
I have a method to get the users by name like below,
public User findByName(String name);如果我尝试使用此方法,则会收到错误消息,
If I try to hit this method am getting an error that,
未找到能够将org.bson.types.ObjectId类型转换为java.lang.String类型的转换器
No converter found capable of converting from type org.bson.types.ObjectId to type java.lang.String
所以我如下更改了User实体类,
So I changed my User entity class as like below,
而不是private List<Claim> claim;
更改为Private List<ObjectId> claim;
现在,如果我执行一个方法(findByName),则会得到一个同时具有两个索赔对象ID("52ffc4a5d85242602e000001","52ffc4a5d85242602e000000")的用户对象,然后迭代索赔清单并获得与索赔对象ID相对应的索赔详细信息.
Now if I execute a method(findByName), I get a user object that has both claim object ids ("52ffc4a5d85242602e000001","52ffc4a5d85242602e000000") then iterate the claim list and get the claim details corresponding to the claim object Id.
代替执行此操作,当我执行findByName方法时,我想获取用户并声明详细信息.如何实现此功能
Instead of doing this, when I execute findByName method I want to get a user and claim details. How can I achieve this functionality
推荐答案如果使用@DBRef引用User类中的Claim,则JSON不仅应包含ID,还应包含对集合的引用,其中也可以找到ID,例如:
If you reference your Claims in the User class with @DBRef, your JSON should not only contain the ID but the reference to the collection where to find the ID as well, like this:
{ "name" : "KSK", "claim" : [ { "$ref":"claim", // the target collection "$id : "ObjectId("52ffc4a5d85242602e000000") } ] }Spring-Data就是这样将Java对象映射到MongoDB的.如果从空白数据库开始,让Spring创建和保存关系,则使用
That is how Spring-Data maps your Java objects to MongoDB. If you start with a blank database and let Spring create and save the relations, you should have no problems using
@DBRef List<Claim> claims;更多推荐
春季Mongo DB @DBREF
发布评论