Spring MongoDB在保存后获取插入项目的ID

编程入门 行业动态 更新时间:2024-10-23 17:33:27
本文介绍了Spring MongoDB在保存后获取插入项目的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用Spring MongoDb.

I am working with Spring MongoDb.

我使用insert方法创建各种实体: docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoOperations.html#insert-java.lang.Object-

I create various entities using insert method: docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoOperations.html#insert-java.lang.Object-

但是,所有方法都返回void.我需要返回插入文档的ObjectId.

However, all methods return void. I need to return the ObjectId of the inserted document.

获得它的最好方法是什么?

What is the best way to get it?

推荐答案

这很有趣,我想分享一下.我只是在上面的BatScream评论的帮助下找到了解决方案:

This is pretty interesting and thought I would share. I just figured out the solution for this with the help of BatScream comment above:

您将创建一个对象并将其插入到MongoDB中:

You would create an object and insert it into your MongoDB:

Animal animal = new Animal(); animal.setName(name); animal.setCat(cat); mongoTemplate.insert(animal);

您的动物类如下所示,其中包含所有字段的吸气剂和设置:

Your animal class looks like this with getters and settings for all fields:

public class Animal { @Id @JsonProperty private String id; @JsonProperty private String name; @JsonProperty private String cat; public String getId() { return id; } }

在mongoTemplate.insert(animal);下完成插入后,您实际上可以调用方法animal.getId(),它将返回创建的ObjectId.

AFTER you have done the insert under mongoTemplate.insert(animal);, you can actually call the method animal.getId() and it will return back the ObjectId that was created.

更多推荐

Spring MongoDB在保存后获取插入项目的ID

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

发布评论

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

>www.elefans.com

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