All Downloads are FREE. Search and download functionalities are using the official Maven repository.

eu.dozd.mongo.MapperCodecProvider Maven / Gradle / Ivy

package eu.dozd.mongo;

import eu.dozd.mongo.annotation.Embedded;
import eu.dozd.mongo.annotation.Entity;
import org.atteo.classindex.ClassIndex;
import org.bson.codecs.Codec;
import org.bson.codecs.configuration.CodecProvider;
import org.bson.codecs.configuration.CodecRegistry;

import java.util.HashMap;
import java.util.Map;

/**
 * Mongo codec provider for mapped entites. Should be passed to Mongo configuration with other providers.
 */
public class MapperCodecProvider implements CodecProvider {
    private Map entityMap = new HashMap<>();

    public MapperCodecProvider() {
        // Standard mapped classes.
        for (Class klass : ClassIndex.getAnnotated(Entity.class)) {
            EntityInfo info = new EntityInfoWithId(klass);
            entityMap.put(klass, info);
        }

        // Process embedded (without id) classes.
        for (Class klass : ClassIndex.getAnnotated(Embedded.class)) {
            EntityInfo info = new EntityInfo(klass);
            entityMap.put(klass, info);
        }
    }

    @Override
    public  Codec get(final Class clazz, final CodecRegistry registry) {
        EntityInfo info = entityMap.get(clazz);

        // CodecProvider returns null if it's not a provider for the requresed Class.
        if (info == null) {
            return null;
        }

        // Create codec for given class.
        return new EntityCodec<>(clazz, info);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy