Coder Social home page Coder Social logo

mongo-jackson-codec's Introduction

mongo-jackson-codec

Mongo Codec using Jackson (and bson4jackson) for serialization

Usage

Synchronous driver

CodecRegistry codecRegistry = CodecRegistries.fromRegistries(MongoClient.getDefaultCodecRegistry(),
                                                             CodecRegistries.fromProviders(new JacksonCodecProvider(ObjectMapperFactory.createObjectMapper())));

MongoClientOptions clientOptions = MongoClientOptions.builder()
                                                 .codecRegistry(codecRegistry)
                                                 .build();

MongoClient client = new MongoClient(new ServerAddress(), clientOptions);

MongoCollection<BlogPost> blogPosts = client.getDatabase("blog").getCollection("posts", BlogPost.class);

BlogPost blogPost1 = new BlogPost("/first_blog",
                              asList(new BlogPostComment(1, "First Comment"), new BlogPostComment(2, "Second Comment")));

BlogPost blogPost2 = new BlogPost("/second_blog",
                              asList(new BlogPostComment(2, "First Comment"), new BlogPostComment(2, "Second Comment")));

blogPosts.insertMany(asList(blogPost1, blogPost2));

List<BlogPost> allBlogPosts = blogPosts.find().into(new ArrayList<>());

Asynchronous driver

MongoClient client = MongoClients.create();

CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
        MongoClients.getDefaultCodecRegistry(), CodecRegistries.fromProviders(
                new ObjectCodecProvider(ObjectMapperFactory.createObjectMapper())));

MongoDatabase database = client.getDatabase("blog").withCodecRegistry(codecRegistry);

MongoCollection<BlogPost> blogPosts = database.getCollection("posts", BlogPost.class);

BlogPost blogPost1 = new BlogPost("/first_blog",
        asList(new BlogPostComment(1, "First Comment"), new BlogPostComment(2, "Second Comment")));

BlogPost blogPost2 = new BlogPost("/second_blog",
        asList(new BlogPostComment(2, "First Comment"), new BlogPostComment(2, "Second Comment")));

blogPosts.insertMany(asList(blogPost1, blogPost2), new SingleResultCallback<Void>() {
    @Override
    public void onResult(Void aVoid, Throwable throwable) {

    }
});

blogPosts.find().into(new ArrayList<>(), new SingleResultCallback<ArrayList<BlogPost>>() {
    @Override
    public void onResult(ArrayList<BlogPost> blogPosts, Throwable throwable) {

    }
});

Mapping

If you want to have ObjectId represented as String, annotate your field with @Id

Dependency.

Maven

<dependency>
  <groupId>fr.javatic.mongo</groupId>
  <artifactId>mongo-jackson-codec</artifactId>
  <version>3.2.2__0.5</version>
  <scope>compile</scope>
</dependency>

Gradle

repositories {
    maven { url "https://dl.bintray.com/ylemoigne/maven" }
}

dependencies {
    compile 'fr.javatic.mongo:mongo-jackson-codec:3.2.2__0.5'
}

SBT

resolvers += "ylemoigne" at "https://dl.bintray.com/ylemoigne/maven"

libraryDependencies += "fr.javatic.mongo" % "mongo-jackson-codec" % "3.2.2__0.5"

Changelog

0.1 Initial Release

0.2 Update to mongo 3.0.4 + test (thanks to https://github.com/mkmelin)

0.3 Update to mongo 3.2.0 + documentation improvement (thanks to greenled)

0.4 @Id serializer/deserializer try to write standard json if JsonGenerator/JsonParser are not BSON

0.5 Update mongo driver (from 3.2.0 to 3.2.2) and bson4jackson (from 2.6.0 to 2.7.0) dependency.

mongo-jackson-codec's People

Contributors

jyemin avatar ylemoigne avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

mongo-jackson-codec's Issues

Find using Java 8 time on collection fails with BsonSerializationExecption

I'm trying to do a find on a collection using a OffsetDateTime as one of the find parameters. For example
collection.find(and(eq("config_key", "foo"), lt("started_at", OffsetDateTime.now()))).first(); returns the exception below. I am registering the JavaTimeBsonModule correctly before connecting to the database as I am able to serialize classes containing OffsetDateTimes just fine. This example also does not work with ZonedDateTime and Instant.

2016-06-20T20:16:22.009953849Z Exception in thread "main" org.bson.BsonSerializationException: Detected unknown BSON type "\x55" for fieldname "�". Are you using the latest driver version?
2016-06-20T20:16:22.012424329Z  at org.bson.BsonBinaryReader.readBsonType(BsonBinaryReader.java:94)
2016-06-20T20:16:22.013202845Z  at org.bson.AbstractBsonWriter.pipeDocument(AbstractBsonWriter.java:698)
2016-06-20T20:16:22.014603469Z  at org.bson.AbstractBsonWriter.pipe(AbstractBsonWriter.java:692)
2016-06-20T20:16:22.015978394Z  at org.bson.codecs.RawBsonDocumentCodec.encode(RawBsonDocumentCodec.java:49)
2016-06-20T20:16:22.022486832Z  at org.bson.codecs.RawBsonDocumentCodec.encode(RawBsonDocumentCodec.java:37)Listening for transport dt_socket at address: 33333
2016-06-20T20:16:22.022536944Z 
2016-06-20T20:16:22.025803344Z  at fr.javatic.mongo.jacksonCodec.JacksonCodec.encode(JacksonCodec.java:58)
2016-06-20T20:16:22.025845758Z  at com.mongodb.client.model.BuildersHelper.encodeValue(BuildersHelper.java:35)
2016-06-20T20:16:22.025851109Z  at com.mongodb.client.model.Filters$OperatorFilter.toBsonDocument(Filters.java:878)
2016-06-20T20:16:22.025856020Z  at com.mongodb.FindIterableImpl.createQueryOperation(FindIterableImpl.java:172)
2016-06-20T20:16:22.025859971Z  at com.mongodb.FindIterableImpl.execute(FindIterableImpl.java:167)
2016-06-20T20:16:22.025863329Z  at com.mongodb.FindIterableImpl.first(FindIterableImpl.java:148)

There is a workaround where I convert the OffsetDateTime to a Java 7 date before doing the find. collection.find(and(eq("config_key", "foo"), lt("started_at", Date.from(OffsetDateTime.now().toInstant())))).first();

Incompatible with the latest bson4jackson

de.undercouch:bson4jackson:2.9.0 doesn't have de.undercouch.bson4jackson.serializers.BsonSerializer class anymore.
However, this class is imported in
fr.javatic.mongo.jacksonCodec.objectId.IdSerializer and fr.javatic.mongo.jacksonCodec.javaTime.serializers.InstantSerializerBase

Is this library abandoned? Jeff Yemin referenced this library in https://jira.mongodb.org/browse/JAVA-2483

Get Id of inserted document

Hi, I'm using the @id annotation leaving the generation to Mongo, but I'm not sure how to get the generated Id after inserting.
Before switching to the jackson codec, I was using just a plain Document and I was able to get the _id field after doing the insertion.

Any idea?
Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.