Spring Data MongoDB: BigInteger to ObjectId conversion

好久不见. 提交于 2019-12-01 06:05:34
Maciej Walkowiak

You can convert it also manually:

ObjectId convertedId = new ObjectId(bigInteger.toString(16));
Query query = new Query(Criteria.where("_id").is(convertedId));

You probably want to write a custom Spring converter BigInteger => ObjectId and ObjectId => BigInteger.

See the doc part here: http://static.springsource.org/spring-data/data-document/docs/current/reference/html/#d0e2670

------UPDATE------

It seems that this kind of converter already exists in the Spring-Data-MongoDB library: http://static.springsource.org/spring-data/data-document/docs/1.0.0.M1/api/org/springframework/data/document/mongodb/SimpleMongoConverter.ObjectIdToBigIntegerConverter.html

So you just have to specify it in your Spring configuration.

Alternatively you can add an 'id' field to your collection classes or potentially a base class and annotate it with org.springframework.data.annotation.Id, as below:

import org.springframework.data.annotation.Id;

public abstract class BaseDocument {

    @Id
    protected long id;

This will allow you to perform the queries of the form:

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

Annotating your own id field with '@Id' will store your id as the mongo objectId, therefore saving you from doing the conversion yourself.

Ramana
//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);

You can convert a BigIngeter to ObjectId using the hex representation of the BigInteger. However, an ObjectId is supposed to be exactly 24 characters long, and parsing a shorter string will fail in Java. Thus it's better to ensure that the hex representation is 0-padded appropriately:

String hexString24 = StringUtils.leftPad(bigInteger.toString(16), 24, "0");
ObjectId convertedId = new ObjectId(hexString24);
Query query = new Query(Criteria.where("_id").is(convertedId));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!