简体   繁体   English

Spring Data MongoDb findById 不返回结果

[英]Spring Data MongoDb findById not returning results

I have a Snozberry object that looks like this:我有一个如下所示的 Snozberry 对象:

 {
  "id":"3cbdb746-561d-4e21-82e0-b7cfcad3a094",
  "thingId":"7cbfb7a6-763d-6ef1-271b-b2a0cfc2fa43",
  "stuffId":81,
  "bits":"WooHoo"
 }

Java class (constructor, getter & setters omitted for brevity): Java 类(为简洁起见,省略了构造函数、getter 和 setter):

@Document(collection="Snozberry")
public class Snozberry {
 @Id
 private UUID id;
 private UUID thingId;
 private Long stuffId;
 private String bits;
}

The repository looks like:存储库如下所示:

public interface SnozberryRepository extends MongoRepository<Snozberry,UUID>{
 Snozberry findByThingId(UUID Id);
 Snozberry findById(UUID id);
}

In the MongoDb collection, the _id & thingId fields are defined as a UUID.在 MongoDb 集合中,_id 和 thingId 字段被定义为 UUID。 I would like to return the document that matches the id value I pass in.我想返回与我传入的 id 值匹配的文档。

I can return all objects using findAll() and I can return objects matching thingId by using the我可以使用 findAll() 返回所有对象,我可以使用返回匹配 thingId 的对象

  Snozberry findByThingId(UUID id)

method defined in my repository, so I know it's talking to the DB ok, and that it can find (non Id) UUID fields ok.在我的存储库中定义的方法,所以我知道它正在与 DB 对话,并且它可以找到(非 Id)UUID 字段。

I've tried the default我试过默认的

findOne(UUID.fromString("3cbdb746-561d-4e21-82e0-b7cfcad3a094")

and i've also called this method defined in the repository我还调用了存储库中定义的这个方法

Snozberry findById(UUID id)

But both of those return null.但是这两个都返回null。 What am I missing (feels like it's something that should be obvious).我错过了什么(感觉应该是显而易见的)。

Thanks M谢谢米

Most probably your problem lies with _id field generated by MongoDB.很可能您的问题在于 MongoDB 生成的 _id 字段。 Since you already have an id field in you class MongoDB will try to do several things to make use of it, if not it will assign it's own _id, take a look at below page由于您的课程中已经有一个 id 字段,MongoDB 将尝试做几件事来利用它,如果没有,它将分配它自己的 _id,看看下面的页面

http://docs.spring.io/spring-data/mongodb/docs/1.2.0.RELEASE/reference/html/mapping-chapter.html http://docs.spring.io/spring-data/mongodb/docs/1.2.0.RELEASE/reference/html/mapping-chapter.html

Go to section 7.1.1 How the '_id' field is handled in the mapping layer转到第7.1.1 节“_id”字段在映射层中的处理方式

and see if it helps.看看它是否有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM