dozd / mongo-mapper Goto Github PK
View Code? Open in Web Editor NEWEasy POJO codec for MongoDB in Java
License: Apache License 2.0
Easy POJO codec for MongoDB in Java
License: Apache License 2.0
There are certain classes that do not need an ID attribute. I suggest using the @Embedded
annotation for classes that do not live outside other documents. Like in Morphia.
I use Spring Data MongoDB in my project. Spring falls short in supporting latest features of MongoDB, so I need resort to using native MongoDB Java driver. It would be really good if there was any way to reuse existing Spring annotations instead of custom annotations specific to this library. I am sure there are other people around with similar situation. Any thoughts on it?
Hello
I am using the following POJO to insert and retrieve data. The insert goes ok but the retrieval gives the following error:
org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class java.util.ArrayList.
at org.bson.codecs.configuration.CodecCache.getOrThrow(CodecCache.java:46)
at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:63)
at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:37)
at com.mongodb.client.model.BuildersHelper.encodeValue(BuildersHelper.java:35)
at com.mongodb.client.model.Filters$SimpleEncodingFilter.toBsonDocument(Filters.java:1078)
at com.mongodb.client.model.Filters$AndFilter.toBsonDocument(Filters.java:915)
at com.mongodb.FindIterableImpl.createQueryOperation(FindIterableImpl.java:229)
at com.mongodb.FindIterableImpl.execute(FindIterableImpl.java:224)
at com.mongodb.FindIterableImpl.first(FindIterableImpl.java:205)
at com.serenity.common.helpers.MongoDbClientsCollectionMongoMapperHelper.getClient(MongoDbClientsCollectionMongoMapperHelper.java:74)
at com.serenity.db.StepsDef.dbStepsDef.thisClientShouldBeFoundInTheDatabase(dbStepsDef.java:100)
at ✽.Then this client should be found in the database(MongoDb.feature:11)
Main class of the POJO
package com.serenity.common.dtos.mongodb;
import eu.dozd.mongo.annotation.Entity;
import eu.dozd.mongo.annotation.Id;
import java.util.List;
import java.util.UUID;
/**
* Created by demian on 6/11/17.
*/
@Entity
public class ClientsDtoMongoMapper
{
// region getters and setters
public String get_id()
{
return _id;
}
public void set_id(String _id)
{
this._id = _id;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public List<ClientAddressDtoMongoMapper> getAddresses()
{
return addresses;
}
public void setAddresses(List<ClientAddressDtoMongoMapper> addresses)
{
this.addresses = addresses;
}
// endregion
@Id
private String _id;
private String firstName;
private String lastName;
public List<ClientAddressDtoMongoMapper> addresses;
public ClientsDtoMongoMapper()
{
}
public ClientsDtoMongoMapper(String firstName, String lastName, List<ClientAddressDtoMongoMapper> addresses)
{
this.set_id(UUID.randomUUID().toString());
this.setFirstName(firstName);
this.setLastName(lastName);
this.addresses = addresses;
}
@Override
public boolean equals(Object client)
{
if (this.get_id().equals(((ClientsDtoMongoMapper) client).get_id()) &&
this.getFirstName().equals(((ClientsDtoMongoMapper) client).getFirstName()) &&
this.getLastName().equals(((ClientsDtoMongoMapper) client).getLastName()) &&
this.addresses.equals(((ClientsDtoMongoMapper) client).getAddresses()))
{
return true;
}
return false;
}
}
Embedded addresses class
package com.serenity.common.dtos.mongodb;
import eu.dozd.mongo.annotation.Embedded;
/**
* Created by demian on 6/11/17.
*/
@Embedded
public class ClientAddressDtoMongoMapper
{
// region getters and setters
public String getStreet()
{
return street;
}
public void setStreet(String street)
{
this.street = street;
}
public String getNumber()
{
return number;
}
public void setNumber(String number)
{
this.number = number;
}
public String getPostalCode()
{
return postalCode;
}
public void setPostalCode(String postalCode)
{
this.postalCode = postalCode;
}
// endregion
private String street;
private String number;
private String postalCode;
public ClientAddressDtoMongoMapper()
{
}
public ClientAddressDtoMongoMapper(String street, String number, String postalCode)
{
this.street = street;
this.number = number;
this.postalCode = postalCode;
}
@Override
public boolean equals(Object client)
{
if (this.getNumber().equals(((ClientAddressDtoMongoMapper) client).getNumber()) &&
this.getPostalCode().equals(((ClientAddressDtoMongoMapper) client).getPostalCode()) &&
this.getStreet().equals(((ClientAddressDtoMongoMapper) client).getStreet()))
{
return true;
}
return false;
}
}
Function used to initialize the mongocollection variable
final MongoCollection mongoCollection;
public MongoDbClientsCollectionMongoMapperHelper(String mongoDbConnectionString, String databaseName, String collectionName)
{
CodecRegistry codecRegistry = CodecRegistries.fromProviders(MongoMapper.getProviders());
MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder();
optionsBuilder.codecRegistry(codecRegistry);
MongoClient mongoClient = new MongoClient(new MongoClientURI(mongoDbConnectionString, optionsBuilder));
MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);
this.mongoCollection = mongoDatabase.getCollection(collectionName, ClientsDtoMongoMapper.class);
}
Code used to get the list of objects of type Client of the database
public List<ClientsDtoMongoMapper> getClient(ClientsDtoMongoMapper client)
{
Bson filter = Filters.and(eq("lastName", client.getLastName()),
eq("firstName", client.getFirstName()),
eq("addresses", client.addresses));
List<ClientsDtoMongoMapper> clients = mongoCollection.find(filter).into(new ArrayList<>());
return clients;
}
Error:
Exception` in thread "main" org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class mongo.TestEntity.
Seem to be related to missing META-INF/annotations/eu.dozd.mongo.annotation.Entity
The question is how do I convince Eclipse and probably other IDEs to generate that file.
Hi, I've been using this library for a while now.
I'm trying to test some stuff with arquillian using some in memory mongo instance:
The thing is the codecs doesn't seem to be registering so i get:
CodecConfigurationException: Can't find a codec for class coop.magnesium.db.entities.Tool.
any thoughts?
thank you.
When the mapping cannot be achieved, it does not throw ant exception neither message.
In my case, having an entity saved in mongo { name: String }
but having declared
class Something {
public String name;
public Object notexistantindb;
}
Will fail silently and I find it concerning when evolving the Scheme.
PD: ¿Can you point me to some other libs that use the async driver?
Hi,
i have the following code:
Parent:
@Entity
public class Parent {
@Id
private String id;
private Map<String, Child> childs;
// getter, setter
}
Child:
@Embedded
public class Child {
private String name;
// getter, setter
}
Main:
public static void main(String[] args) {
// ...
Parent parent = new Parent();
parent.setId("parent1");
Child child = new Child();
child.setName("child1");
parent.setChilds(new HashMap<String, Child>());
parent.getChilds().put(child.getName(), child);
mapperTest.insertOne(parent);
Parent parent2 = mapperTest.find().first();
Map<String, Child> children = parent2.getChilds();
Child child1 = children.get(child.getName()); // <- ClassCastException
}
The following Json is inserted into mongoDB:
{
"_id" : "parent1",
"childs" : {
"child1" : {
"name" : "child1"
}
}
}
The following code throws a ClassCastException:
Exception in thread "main" java.lang.ClassCastException: org.bson.Document cannot be cast to Child
When i inspect the class parent2
(the one that is filled with the values read from the db) the values of Map childs
are of type bson.Document
and not Child
. See screenshot below:
The same exception occurs, when I add another child.
Is it possible, that the Map<String, Child> is not recognized or mapped correctly?
Very helpful for updates, if a document has a new int field with default value x.
Currently you have to update all document in an manual process before release, otherwise the documents can't be read.
java.lang.ClassCastException: org.bson.types.ObjectId cannot be cast to java.lang.String
at eu.dozd.mongo.EntityCodec.decode(EntityCodec.java:95)
The error is in the if
block of the following loop in EntityCodec.java
:
for (String field : info.getFields()) {
if (field.equals(info.getIdField())) {
info.setId(t, (String) document.get(ID_FIELD));
} else {
Object o;
o = document.get(field);
if (info.getFieldType(field).isEnum()) {
o = o == null ? null : Enum.valueOf((Class<? extends Enum>) info.getFieldType(field), (String) o);
}
info.setValue(t, field, o);
}
}
Why not have the ID field be an ObjectId
? Seems like that might be preferable anyway.
Hi there,
JSON in MongoDB 3.x:
{
"_id" : "somehex",
"name" : "a Name",
"someobject": null
}
Class to map to:
@Entity
public class MyClass {
@Id
@JsonProperty
private String id;
@NotEmpty
@JsonProperty
private String name;
@JsonProperty
private SomeObject someobject;
}
My code, that retrieves the values from mongodb:
FindIterable<MyClass> myClasses = myClassCollection.find(query.toBson(true));
return myClasses.into(new ArrayList<MyClass>());
When i try to map this back to a class it gives me an error:
readStartDocument can only be called when CurrentBSONType is DOCUMENT, not when CurrentBSONType is NULL.
Stacktrace:
ERROR [2017-01-07 15:03:58,066] com.washingtonpost.dropwizard.exceptions.mappers.RuntimeExceptionMapper: readStartDocument can only be called when CurrentBSONType is DOCUMENT, not when CurrentBSONType is NULL.
! org.bson.BsonInvalidOperationException: readStartDocument can only be called when CurrentBSONType is DOCUMENT, not when CurrentBSONType is NULL.
! at org.bson.AbstractBsonReader.verifyBSONType(AbstractBsonReader.java:692)
! at org.bson.AbstractBsonReader.checkPreconditions(AbstractBsonReader.java:724)
! at org.bson.AbstractBsonReader.readStartDocument(AbstractBsonReader.java:452)
! at eu.dozd.mongo.EntityCodec.decode(EntityCodec.java:63)
! at eu.dozd.mongo.EntityCodec.decode(EntityCodec.java:69)
! at com.mongodb.operation.CommandResultArrayCodec.decode(CommandResultArrayCodec.java:52)
! at com.mongodb.operation.CommandResultDocumentCodec.readValue(CommandResultDocumentCodec.java:53)
! at org.bson.codecs.BsonDocumentCodec.decode(BsonDocumentCodec.java:84)
! at org.bson.codecs.BsonDocumentCodec.decode(BsonDocumentCodec.java:41)
! at org.bson.codecs.configuration.LazyCodec.decode(LazyCodec.java:47)
! at org.bson.codecs.BsonDocumentCodec.readValue(BsonDocumentCodec.java:101)
! at com.mongodb.operation.CommandResultDocumentCodec.readValue(CommandResultDocumentCodec.java:56)
! at org.bson.codecs.BsonDocumentCodec.decode(BsonDocumentCodec.java:84)
! at org.bson.codecs.BsonDocumentCodec.decode(BsonDocumentCodec.java:41)
! at com.mongodb.connection.ReplyMessage.<init>(ReplyMessage.java:57)
! at com.mongodb.connection.CommandProtocol.getResponseDocument(CommandProtocol.java:139)
! at com.mongodb.connection.CommandProtocol.execute(CommandProtocol.java:118)
! at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:168)
! at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:289)
! at com.mongodb.connection.DefaultServerConnection.command(DefaultServerConnection.java:176)
! at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:216)
! at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:207)
! at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:113)
! at com.mongodb.operation.FindOperation$1.call(FindOperation.java:516)
! at com.mongodb.operation.FindOperation$1.call(FindOperation.java:510)
! at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:431)
! at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:404)
! at com.mongodb.operation.FindOperation.execute(FindOperation.java:510)
! at com.mongodb.operation.FindOperation.execute(FindOperation.java:81)
! at com.mongodb.Mongo.execute(Mongo.java:836)
! at com.mongodb.Mongo$2.execute(Mongo.java:823)
! at com.mongodb.OperationIterable.iterator(OperationIterable.java:47)
! at com.mongodb.OperationIterable.forEach(OperationIterable.java:70)
! at com.mongodb.OperationIterable.into(OperationIterable.java:82)
! at com.mongodb.FindIterableImpl.into(FindIterableImpl.java:171)
.
.
.
How can i fix this? Is this an error when mapping back to POJOs?
Thanks!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.