Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data MongoDB: BigInteger to ObjectId conversion

I have a problem with update query using Spring Data MongoDB. I retrieve some object's _id as BigInteger value. Then I want to make following query:

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

Query part fails to match any documents since id value passed to is() somehow must be converted to ObjectId. I can't find any documentation on this kind of conversion. Will appreciate any help.

p.s.: SpringData Mongodb version 1.2

like image 732
Aleksandr Kravets Avatar asked Jul 08 '13 15:07

Aleksandr Kravets


3 Answers

You can convert it also manually:

ObjectId convertedId = new ObjectId(bigInteger.toString(16));
Query query = new Query(Criteria.where("_id").is(convertedId));
like image 86
Maciej Walkowiak Avatar answered Nov 14 '22 22:11

Maciej Walkowiak


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.

like image 45
Mik378 Avatar answered Nov 14 '22 21:11

Mik378


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.

like image 26
Trevor Gowing Avatar answered Nov 14 '22 22:11

Trevor Gowing