简体   繁体   English

使用 MongoTemplate 时如何将类型从 ObjectId 转换为 Long?

[英]How to convert type from ObjectId to Long when using MongoTemplate?

Normally when using spring data repositories, an object in which the result data can be stored is needed like the customer in this example: https://spring.io/guides/gs/accessing-data-mongodb/ .通常在使用 spring 数据存储库时,需要一个 object 可以存储结果数据,如本例中的客户: https/gs ./accessings://data-mongodb/guide

In my case I'm trying to use an object which is declared in another project I'm importing using maven - let's call it MyDoc .在我的情况下,我正在尝试使用在另一个项目中声明的 object,它在我使用 maven 导入的另一个项目中声明 - 我们称之为MyDoc The object has an attribute Long id while the document in the MongoDB has an addition field _id from type ObjectId . object 具有属性Long id而 MongoDB 中的文档具有来自类型ObjectId的附加字段_id This btw is like this because the MongoDB serves as an archive and the actual id from MyDoc would not be unique.顺便说一句,这是因为 MongoDB 用作存档,而来自 MyDoc 的实际id不会是唯一的。

In a service class I then use this the MongoTemplate to make database queries like this:在服务 class 然后我使用这个 MongoTemplate 进行数据库查询,如下所示:

List<MyDoc> list = template.findAll(MyDoc.class, "DOCS");
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [org.bson.types.ObjectId] to type [java.lang.Long] 

How can I convert the ObjectId to a type of Long?如何将 ObjectId 转换为 Long 类型?

Alternately, I could, of course, use the java MongoDB driver but I wanted to reduce the number of dependencies to maintain since the MongoDB driver comes with the boot-starter-data-MongoDB dependency, and also hoped for a more intuitive way, in the end, to interact with the database like with the spring data repositories.或者,我当然可以使用 java MongoDB 驱动程序,但我想减少要维护的依赖项的数量,因为 MongoDB 驱动程序带有更直观的引导启动数据方式,MongoDB 驱动程序带有引导启动器和数据方式最后,与数据库进行交互,就像使用 spring 数据存储库一样。

First thing is Long Id from MyDoc is not unique, so it cannot act as _id of mongoDB.首先是来自 MyDoc 的Long Id不是唯一的,因此它不能充当 mongoDB 的 _id。 Then you need to have one more _id field in your class.然后,您需要在 class 中再添加一个 _id 字段。 By Default Spring data mongoDB will map field named id to _id in dataBase.默认情况下 Spring 数据 mongoDB 将 map 字段名为 id 到数据库中的 _id。 Essentially what you can do is create a wrapper class around MyDoc by extending it and then add new field of Type ObjectId and annotate it with @Id .本质上,您可以做的是通过扩展MyDoc创建一个包装器 class ,然后添加 Type ObjectId的新字段并使用@Id对其进行注释。 By that way you will have unique index and also mongoTemplate will not try to convert _id of database to Long id通过这种方式,您将拥有唯一索引,并且 mongoTemplate 也不会尝试将数据库的_id转换为Long id

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

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