SlideShare a Scribd company logo
1 of 11
Using Jackson with MongoDB

         08/08/2012
        Ramesh Pidikiti
Background
• Mongo Stores documents in JSON format
• Jackson plays roles in serializing and de-
  serializing java/scala objects
Options
• What are my options for serialization and
  deserialization
  – Manual
  – Jackson
  – Morphia
• Which one should I use?
Options Continued
• One solution doesn’t fit all
• Jackson provides following advantages
   – Faster to development compared to Manual technique
   – Unified annotations across all layers compared to Morphia
   – Handles the types more friendlier way, example: Changing
     data type from long to int is transparently handled by
     jackson compared to manual technique
   – We can also have different mappers between DB and
     Jersey layers (Example: Date format in REST calls can be
     different from date formats in mongo)
•   Saving object using Jackson

    TestObjectWithDate obj= new TestObjectWithDate(1, "String 1",1, new Date());
    DBObject dbo = (DBObject)JSON.parse(mapper.writeValueAsString(obj));
    coll.save(dbo);



•   Saving object using manual mapping (this is top level object, if more levels in
    object graph , this code can definitely much more lengthier)

    TestObjectWithDate obj2 = new TestObjectWithDate(1, "String 1",1, new Date());
     BasicDBObject dbo2 = new BasicDBObject();
     dbo.put("_id", obj.getId());
     dbo.put("stringVal", obj.getStringVal());
•
     dbo.put("longVal", obj.getLongVal());
     dbo.put("dateVal", obj.getDateVal());
     coll.save(dbo2);
• Retrieve object using Jackson
    DBObject queryObj = coll.findOne();
    TestObjectWithDate afterSave = mapper.readValue(queryObj.toString(),TestObjectWithDate.class);




•   Retrieve object using manual mapping

    BasicDBObject dbObj = (BasicDBObject)coll.findOne();
    TestObjectWithDate obj= new TestObjectWithDate();
    obj.setId(dbObj.getLong("_id"));
    obj.setStringVal(dbObj.getString("stringVal"));
    obj.setLongVal(dbObj.getLong("longVal"));
    obj.setDateVal((Date)dbo.get("dateVal"));
Challenges
• Mongo stores dates in bson format so we
  need custom serializer and deserializer for
  date data type
  Regular Date output:
  {dt: "2012-08-03T14:57:40.813Z"}

  For mongo to store using date data type we need following format
  {dt:{“$date “:"2012-08-03T14:57:40.813Z"}}
public class BsonDateSerializer extends StdSerializer<Date> {

    public BsonDateSerializer() {
      super(Date.class);
    }

    @Override
    public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
      jgen.writeStartObject();
      serializeContents(value, jgen, provider);
      jgen.writeEndObject();
    }

    private void serializeContents(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
      jgen.writeFieldName("$date");
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
      jgen.writeString(dateFormat.format(value));
    }

}
public class BsonDateDeserializer extends JsonDeserializer<Date> {

    public BsonDateDeserializer() {

    }

    public Date deserialize(JsonParser jp, com.fasterxml.jackson.databind.DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
      JsonNode tree = jp.readValueAsTree();
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
      try{
        return dateFormat.parse(tree.get("$date").textValue());
      }catch(Throwable t){
        throw new IOException(t.getMessage(), t);
      }
    }

}



How fast is Jackson compared to other options?
Benchmarks
     •    Mac OS X, 10.7.3, 2.4 GHz, i7, 8GB, 1333 MHz, DDR3 machine

250000                                                                                       238095




200000

                                                                                                                  170357     173010
                                                                                                      158227

150000




100000




50000                                              38183
                                                            26205       27624      28296

          6461     3792        3925       4379
     0
         Manual   Jackson    Jackson 2   Morphia   Manual   Jackson    Jackson 2   Morphia   Manual   Jackson    Jackson 2   Morphia

                      Full Object                                One level                                 Top level
Benchmarks
• Manual
  –   Full, objects: 100000, rate: 6461.2 / sec, throughput: 47.15 mb/sec
  –   one-level, objects: 100000, rate: 38182.51 / sec, throughput: 27.5 mb/sec
  –   top-level, objects: 100000, rate: 238095.24 / sec, throughput: 20.61 mb/sec


• Jackson
  –   Full, objects: 100000, , rate: 3792.04, throughput: 27.67 mb/sec
  –   one-level, objects: 100000, rate: 26205.45, throughput: 18.87 mb/sec
  –   top-level, objects: 100000, ate: 158227.85, throughput: 13.7 mb/sec


• Jackson2
  –   Full, objects: 100000, rate: 3925.57, throughput: 28.64 mb/sec
  –   one-level, objects: 100000, rate: 27624.31, throughput: 19.89 mb/sec
  –   top-level, objects: 100000, rate: 170357.75, throughput: 14.75 mb/sec


• Morphia
  –   Full, objects: 100000, rate: 4379.43, throughput: 31.96 mb/sec
  –   one-level, objects: 100000, rate: 27624.31, throughput: 19.89 mb/sec
  –   top-level, objects: 100000, rate: 173010.38, throughput: 14.98 mb/sec

More Related Content

Similar to Jackson with mongo db

IT Days - Parse huge JSON files in a streaming way.pptx
IT Days - Parse huge JSON files in a streaming way.pptxIT Days - Parse huge JSON files in a streaming way.pptx
IT Days - Parse huge JSON files in a streaming way.pptxAndrei Negruti
 
State of GeoServer at FOSS4G-NA
State of GeoServer at FOSS4G-NAState of GeoServer at FOSS4G-NA
State of GeoServer at FOSS4G-NAGeoSolutions
 
Tour de Jackson: Forgotten Features of Jackson JSON processor
Tour de Jackson: Forgotten Features of Jackson JSON processorTour de Jackson: Forgotten Features of Jackson JSON processor
Tour de Jackson: Forgotten Features of Jackson JSON processorTatu Saloranta
 
The State of the GeoServer project
The State of the GeoServer projectThe State of the GeoServer project
The State of the GeoServer projectGeoSolutions
 
Representing and Querying Geospatial Information in the Semantic Web
Representing and Querying Geospatial Information in the Semantic WebRepresenting and Querying Geospatial Information in the Semantic Web
Representing and Querying Geospatial Information in the Semantic WebKostis Kyzirakos
 
Quick Wikipedia Mining using Elastic Map Reduce
Quick Wikipedia Mining using Elastic Map ReduceQuick Wikipedia Mining using Elastic Map Reduce
Quick Wikipedia Mining using Elastic Map Reduceohkura
 
Going Native: Leveraging the New JSON Native Datatype in Oracle 21c
Going Native: Leveraging the New JSON Native Datatype in Oracle 21cGoing Native: Leveraging the New JSON Native Datatype in Oracle 21c
Going Native: Leveraging the New JSON Native Datatype in Oracle 21cJim Czuprynski
 
RasterFrames - FOSS4G NA 2018
RasterFrames - FOSS4G NA 2018RasterFrames - FOSS4G NA 2018
RasterFrames - FOSS4G NA 2018Simeon Fitch
 
RasterFrames: Enabling Global-Scale Geospatial Machine Learning
RasterFrames: Enabling Global-Scale Geospatial Machine LearningRasterFrames: Enabling Global-Scale Geospatial Machine Learning
RasterFrames: Enabling Global-Scale Geospatial Machine LearningAstraea, Inc.
 
NinjaScript 2010-10-14
NinjaScript 2010-10-14NinjaScript 2010-10-14
NinjaScript 2010-10-14lrdesign
 
Data Types/Structures in DivConq
Data Types/Structures in DivConqData Types/Structures in DivConq
Data Types/Structures in DivConqeTimeline, LLC
 
Sydney Python Presentation (Feb 2010) - Tracking Large Metallic Objects / Goo...
Sydney Python Presentation (Feb 2010) - Tracking Large Metallic Objects / Goo...Sydney Python Presentation (Feb 2010) - Tracking Large Metallic Objects / Goo...
Sydney Python Presentation (Feb 2010) - Tracking Large Metallic Objects / Goo...Kelvin Nicholson
 
FOSS4G 2010 PostGIS Raster: an Open Source alternative to Oracle GeoRaster
FOSS4G 2010 PostGIS Raster: an Open Source alternative to Oracle GeoRasterFOSS4G 2010 PostGIS Raster: an Open Source alternative to Oracle GeoRaster
FOSS4G 2010 PostGIS Raster: an Open Source alternative to Oracle GeoRasterJorge Arevalo
 
Semantic code transformations in MetaJS
Semantic code transformations in MetaJSSemantic code transformations in MetaJS
Semantic code transformations in MetaJSDmytro Dogadailo
 
Ebookrentalfilm
EbookrentalfilmEbookrentalfilm
Ebookrentalfilmdhi her
 
03 2017Emea_RoadshowMilan-WhatsNew-Mariadbserver10_2andmaxscale 2_1
03 2017Emea_RoadshowMilan-WhatsNew-Mariadbserver10_2andmaxscale 2_103 2017Emea_RoadshowMilan-WhatsNew-Mariadbserver10_2andmaxscale 2_1
03 2017Emea_RoadshowMilan-WhatsNew-Mariadbserver10_2andmaxscale 2_1mlraviol
 

Similar to Jackson with mongo db (20)

IT Days - Parse huge JSON files in a streaming way.pptx
IT Days - Parse huge JSON files in a streaming way.pptxIT Days - Parse huge JSON files in a streaming way.pptx
IT Days - Parse huge JSON files in a streaming way.pptx
 
State of GeoServer at FOSS4G-NA
State of GeoServer at FOSS4G-NAState of GeoServer at FOSS4G-NA
State of GeoServer at FOSS4G-NA
 
Tour de Jackson: Forgotten Features of Jackson JSON processor
Tour de Jackson: Forgotten Features of Jackson JSON processorTour de Jackson: Forgotten Features of Jackson JSON processor
Tour de Jackson: Forgotten Features of Jackson JSON processor
 
The State of the GeoServer project
The State of the GeoServer projectThe State of the GeoServer project
The State of the GeoServer project
 
Representing and Querying Geospatial Information in the Semantic Web
Representing and Querying Geospatial Information in the Semantic WebRepresenting and Querying Geospatial Information in the Semantic Web
Representing and Querying Geospatial Information in the Semantic Web
 
Quick Wikipedia Mining using Elastic Map Reduce
Quick Wikipedia Mining using Elastic Map ReduceQuick Wikipedia Mining using Elastic Map Reduce
Quick Wikipedia Mining using Elastic Map Reduce
 
Going Native: Leveraging the New JSON Native Datatype in Oracle 21c
Going Native: Leveraging the New JSON Native Datatype in Oracle 21cGoing Native: Leveraging the New JSON Native Datatype in Oracle 21c
Going Native: Leveraging the New JSON Native Datatype in Oracle 21c
 
Scripting GeoServer
Scripting GeoServerScripting GeoServer
Scripting GeoServer
 
RasterFrames - FOSS4G NA 2018
RasterFrames - FOSS4G NA 2018RasterFrames - FOSS4G NA 2018
RasterFrames - FOSS4G NA 2018
 
RasterFrames: Enabling Global-Scale Geospatial Machine Learning
RasterFrames: Enabling Global-Scale Geospatial Machine LearningRasterFrames: Enabling Global-Scale Geospatial Machine Learning
RasterFrames: Enabling Global-Scale Geospatial Machine Learning
 
huhu
huhuhuhu
huhu
 
MVC 2.0 - A Breakthrough
MVC 2.0 - A BreakthroughMVC 2.0 - A Breakthrough
MVC 2.0 - A Breakthrough
 
NinjaScript 2010-10-14
NinjaScript 2010-10-14NinjaScript 2010-10-14
NinjaScript 2010-10-14
 
Data Types/Structures in DivConq
Data Types/Structures in DivConqData Types/Structures in DivConq
Data Types/Structures in DivConq
 
Sydney Python Presentation (Feb 2010) - Tracking Large Metallic Objects / Goo...
Sydney Python Presentation (Feb 2010) - Tracking Large Metallic Objects / Goo...Sydney Python Presentation (Feb 2010) - Tracking Large Metallic Objects / Goo...
Sydney Python Presentation (Feb 2010) - Tracking Large Metallic Objects / Goo...
 
FOSS4G 2010 PostGIS Raster: an Open Source alternative to Oracle GeoRaster
FOSS4G 2010 PostGIS Raster: an Open Source alternative to Oracle GeoRasterFOSS4G 2010 PostGIS Raster: an Open Source alternative to Oracle GeoRaster
FOSS4G 2010 PostGIS Raster: an Open Source alternative to Oracle GeoRaster
 
Semantic code transformations in MetaJS
Semantic code transformations in MetaJSSemantic code transformations in MetaJS
Semantic code transformations in MetaJS
 
Ebookrentalfilm
EbookrentalfilmEbookrentalfilm
Ebookrentalfilm
 
03 2017Emea_RoadshowMilan-WhatsNew-Mariadbserver10_2andmaxscale 2_1
03 2017Emea_RoadshowMilan-WhatsNew-Mariadbserver10_2andmaxscale 2_103 2017Emea_RoadshowMilan-WhatsNew-Mariadbserver10_2andmaxscale 2_1
03 2017Emea_RoadshowMilan-WhatsNew-Mariadbserver10_2andmaxscale 2_1
 
Pycon2011
Pycon2011Pycon2011
Pycon2011
 

Recently uploaded

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 

Jackson with mongo db

  • 1. Using Jackson with MongoDB 08/08/2012 Ramesh Pidikiti
  • 2. Background • Mongo Stores documents in JSON format • Jackson plays roles in serializing and de- serializing java/scala objects
  • 3. Options • What are my options for serialization and deserialization – Manual – Jackson – Morphia • Which one should I use?
  • 4. Options Continued • One solution doesn’t fit all • Jackson provides following advantages – Faster to development compared to Manual technique – Unified annotations across all layers compared to Morphia – Handles the types more friendlier way, example: Changing data type from long to int is transparently handled by jackson compared to manual technique – We can also have different mappers between DB and Jersey layers (Example: Date format in REST calls can be different from date formats in mongo)
  • 5. Saving object using Jackson TestObjectWithDate obj= new TestObjectWithDate(1, "String 1",1, new Date()); DBObject dbo = (DBObject)JSON.parse(mapper.writeValueAsString(obj)); coll.save(dbo); • Saving object using manual mapping (this is top level object, if more levels in object graph , this code can definitely much more lengthier) TestObjectWithDate obj2 = new TestObjectWithDate(1, "String 1",1, new Date()); BasicDBObject dbo2 = new BasicDBObject(); dbo.put("_id", obj.getId()); dbo.put("stringVal", obj.getStringVal()); • dbo.put("longVal", obj.getLongVal()); dbo.put("dateVal", obj.getDateVal()); coll.save(dbo2);
  • 6. • Retrieve object using Jackson DBObject queryObj = coll.findOne(); TestObjectWithDate afterSave = mapper.readValue(queryObj.toString(),TestObjectWithDate.class); • Retrieve object using manual mapping BasicDBObject dbObj = (BasicDBObject)coll.findOne(); TestObjectWithDate obj= new TestObjectWithDate(); obj.setId(dbObj.getLong("_id")); obj.setStringVal(dbObj.getString("stringVal")); obj.setLongVal(dbObj.getLong("longVal")); obj.setDateVal((Date)dbo.get("dateVal"));
  • 7. Challenges • Mongo stores dates in bson format so we need custom serializer and deserializer for date data type Regular Date output: {dt: "2012-08-03T14:57:40.813Z"} For mongo to store using date data type we need following format {dt:{“$date “:"2012-08-03T14:57:40.813Z"}}
  • 8. public class BsonDateSerializer extends StdSerializer<Date> { public BsonDateSerializer() { super(Date.class); } @Override public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeStartObject(); serializeContents(value, jgen, provider); jgen.writeEndObject(); } private void serializeContents(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeFieldName("$date"); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); jgen.writeString(dateFormat.format(value)); } }
  • 9. public class BsonDateDeserializer extends JsonDeserializer<Date> { public BsonDateDeserializer() { } public Date deserialize(JsonParser jp, com.fasterxml.jackson.databind.DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode tree = jp.readValueAsTree(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); try{ return dateFormat.parse(tree.get("$date").textValue()); }catch(Throwable t){ throw new IOException(t.getMessage(), t); } } } How fast is Jackson compared to other options?
  • 10. Benchmarks • Mac OS X, 10.7.3, 2.4 GHz, i7, 8GB, 1333 MHz, DDR3 machine 250000 238095 200000 170357 173010 158227 150000 100000 50000 38183 26205 27624 28296 6461 3792 3925 4379 0 Manual Jackson Jackson 2 Morphia Manual Jackson Jackson 2 Morphia Manual Jackson Jackson 2 Morphia Full Object One level Top level
  • 11. Benchmarks • Manual – Full, objects: 100000, rate: 6461.2 / sec, throughput: 47.15 mb/sec – one-level, objects: 100000, rate: 38182.51 / sec, throughput: 27.5 mb/sec – top-level, objects: 100000, rate: 238095.24 / sec, throughput: 20.61 mb/sec • Jackson – Full, objects: 100000, , rate: 3792.04, throughput: 27.67 mb/sec – one-level, objects: 100000, rate: 26205.45, throughput: 18.87 mb/sec – top-level, objects: 100000, ate: 158227.85, throughput: 13.7 mb/sec • Jackson2 – Full, objects: 100000, rate: 3925.57, throughput: 28.64 mb/sec – one-level, objects: 100000, rate: 27624.31, throughput: 19.89 mb/sec – top-level, objects: 100000, rate: 170357.75, throughput: 14.75 mb/sec • Morphia – Full, objects: 100000, rate: 4379.43, throughput: 31.96 mb/sec – one-level, objects: 100000, rate: 27624.31, throughput: 19.89 mb/sec – top-level, objects: 100000, rate: 173010.38, throughput: 14.98 mb/sec