Giter Site home page Giter Site logo

mongo-mapper's People

Contributors

dozd avatar gmilev2022 avatar mmithril avatar notz 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  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

mongo-mapper's Issues

.get() on Map and casting to the class which is used in the Map leads to ClassCastException

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:

bildschirmfoto 2017-01-25 um 18 56 44

The same exception occurs, when I add another child.
Is it possible, that the Map<String, Child> is not recognized or mapped correctly?

serialize/map NULL values from db to fields

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!

Error casting ObjectId to String

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.

Any plans to use Spring annotations instead of indigenous ones?

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?

Arquillian Test

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:

de.flapdoodle.embed de.flapdoodle.embed.mongo 2.0.0 test

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.

Support for default Value

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.

Can't run mapper app from within IDE

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.

Silently failing

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?

Error retrieving data with a POJO

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;
    }

Embedded Classes

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.

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.