Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a Mongo Converter for only one field

I have the case that i have a simple POJO with one long field in it, which is actually a timestamp.

This field must be in the mongo database represented by an ISODate.

I could write an Converter fot the whole Pojo, but since it is only one field out of 25 that would not make much sense and is another spot for errors when a field would change or one more gets added.

Is there a way to call the default converter service and change the 2 other after the default converting service which will impact the performance a lot. Or is there a default Converter interface to override?

Whats the best practice here?

Maybe there is an annotation that I can apply to this field?

And yes i could also write an LongToDate Converter, but this would affect all POJOs, not just this single one.

Here the sample POJO:

public class Person {
   private long someTimestamp;
//getters and setters
}

Without converters this would look like this:

{
    "_id" : ObjectId("52ae8eede4b0249cde22059e"),
    "someTimestamp" : NumberLong(1392714950940)
}

Thats how the result should look like:

{
    "_id" : ObjectId("52ae8eede4b0249cde22059e"),
    "someTimestamp" : ISODate("2013-12-23T23:00:00.000Z")
}

The desribed problem gets even more complicated when such a timestampt value is in a nested document for exmaple:

{
    "_id" : ObjectId("52ae8eede4b0249cde22059e"),
    "items" : [
        "someTimestamp" : NumberLong(1392714950940)
    ]
}

POJO:

public class Person {
   private Collection<OtherPojoThatHoldsTimestamps> items;
//getters and setters
}

Maybe I should mention that I am using Spring to accomplish this. (http://projects.spring.io/spring-data-mongodb/)

like image 606
Zarathustra Avatar asked Feb 18 '14 09:02

Zarathustra


1 Answers

It sounds like you need annotation-driven conversion. Section 6.6.2 in the reference manual talks about this for formatters, and even has an example with timestamps.

The general idea is that you'd mark fields which need special handling with an annotation (it's a good use of annotations, you're specifying metadata after all). You'd then register a converter for fields having that annotation.

Problem is I've just tried this and can't get it to work, because metadata is getting lost. I've filed a JIRA ticket to see whether there's a way around this.

like image 65
Emerson Farrugia Avatar answered Nov 14 '22 15:11

Emerson Farrugia