春季Mongo DB @DBREF

编程入门 行业动态 更新时间:2024-10-25 22:27:52
本文介绍了春季Mongo DB @DBREF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是我的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

本文发布于:2023-11-22 21:02:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619009.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:春季   Mongo   DBREF   DB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!