5

我在使用 Spring Data MongoDB 进行更新查询时遇到问题。我检索一些对象的 _id 作为 BigInteger 值。然后我想进行以下查询:

Query query = new Query(Criteria.where("_id").is(id));
Update update = new Update();
update.set("version",version);
mongoOperations.updateFirst(query, update, Audit.class);

查询部分无法匹配任何文档,因为传递给的 id 值is()必须以某种方式转换为 ObjectId。我找不到任何关于这种转换的文档。将不胜感激任何帮助。

ps:SpringData Mongodb 1.2版

4

5 回答 5

6

您也可以手动转换它:

ObjectId convertedId = new ObjectId(bigInteger.toString(16));
Query query = new Query(Criteria.where("_id").is(convertedId));
于 2013-07-12T17:06:50.290 回答
1

或者,您可以将“id”字段添加到您的集合类或可能的基类中,并使用 org.springframework.data.annotation.Id 对其进行注释,如下所示:

import org.springframework.data.annotation.Id;

public abstract class BaseDocument {

    @Id
    protected long id;

这将允许您执行表单的查询:

public boolean doesDocumentExist(Class clazz, long documentId) {
    Query queryCriteria = new Query(Criteria.where("id").is(documentId));
    return mongoTemplate.count(queryCriteria, clazz) == 1;
}

使用“@Id”注释您自己的 id 字段会将您的 id 存储为 mongo objectId,从而避免您自己进行转换。

于 2013-07-09T06:09:13.940 回答
1

您可能想编写一个自定义 Spring 转换器 BigInteger => ObjectId 和 ObjectId => BigInteger。

请参阅此处的文档部分:http: //static.springsource.org/spring-data/data-document/docs/current/reference/html/#d0e2670

- - - 更新 - - -

这种转换器似乎已经存在于 Spring-Data-MongoDB 库中: http ://static.springsource.org/spring-data/data-document/docs/1.0.0.M1/api/org/springframework/数据/文档/mongodb/SimpleMongoConverter.ObjectIdToBigIntegerConverter.html

所以你只需要在你的 Spring 配置中指定它。

于 2013-07-08T16:08:58.287 回答
0
//get the converter from the mongoTemplate

MappingMongoConverter converter = (MappingMongoConverter)mongoTemplate.getConverter();

//get the conversion service from the mongo converter

ConversionService conversionService = converter.getConversionService();

//iterate the status list and get the each id to add the arraylist

for(Status status: statusList){

    ObjectId objectIdVal = conversionService.convert(status.getId(), ObjectId.class);

    **//here status.getId() returns the BigInteger**
    statusArrayList.add(objectIdVal);           
}

//get the users list whose status is active  and cancel

query.addCriteria(new Criteria().where("status.$id").in(statusArrayList));

List<User> usersList = mongoTemplate.find(query, User.class);
于 2014-08-21T05:56:00.703 回答
0

您可以将 a 转换BigIngeterObjectId使用BigInteger. 但是,anObjectId应该正好是 24 个字符长,在 Java 中解析较短的字符串会失败。因此,最好确保适当地填充 0 十六进制表示:

String hexString24 = StringUtils.leftPad(bigInteger.toString(16), 24, "0");
ObjectId convertedId = new ObjectId(hexString24);
Query query = new Query(Criteria.where("_id").is(convertedId));
于 2017-10-01T03:15:52.107 回答