question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Mapping does not work with generic types

See original GitHub issue

Mapping does not work with generic types Using generic types in the @Entity does not work. The UUID gets correctly stored in MongoDB but when reading the Document is not correctly mapped to UUID.

To Reproduce Generic Entity:

@Entity
public class GenericEntity<T> {
	@Id
	protected T id;
	protected T test;

	public T getId() {
		return id;
	}

	public void setId(T id) {
		this.id = id;
	}

	public T getTest() {
		return test;
	}

	public void setTest(T test) {
		this.test = test;
	}
}

Specific Entity:

@Entity
public class SpecifiyEntity extends GenericEntity<UUID> {

}

Main-Class:

	public static void main(String[] args) {

		final Datastore datastore = Morphia.createDatastore(MongoClients.create(
				MongoClientSettings.builder().applyConnectionString(new ConnectionString("mongodb://127.0.0.1/"))
						.uuidRepresentation(UuidRepresentation.STANDARD).build()),
				"morphia_example");

		datastore.getMapper().mapPackage("de.test");

		datastore.ensureIndexes();

		SpecifiyEntity beforeDB = new SpecifiyEntity();
		beforeDB.setId(UUID.randomUUID());
		beforeDB.setTest(UUID.randomUUID());
		datastore.save(beforeDB);

		SpecifiyEntity fromDB = datastore.find(SpecifiyEntity.class).filter(Filters.eq("_id", beforeDB.getId()))
				.iterator().next();

		System.out.println(beforeDB.getId());
		System.out.println(fromDB.getId());

		System.out.println(beforeDB.getTest());
		System.out.println(fromDB.getTest());
	}

Output:

6d7143cb-aa14-4d3f-96c0-fdda5e223ea6
org.bson.types.Binary@80d33fd8
685e8147-7a6f-40b1-a6a2-1da6b1f1bce9
org.bson.types.Binary@d18db8b1

Expected behavior Fields are mapped to the correct type.

  • Server Version: 4.0.17
  • Driver Version: 4.0.2
  • Morphia Version: 2.0.0

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:12 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
Skjivarcommented, Sep 8, 2020

@evanchooly I’m not sure if this a valid solution, but i figured out that after reversing the hirarchy set in dev.morphia.mapping.codec.pojo.EntityModelBuilder.java:241 protected void configure() the mapping works as expected. I used the 2.0.x branch.

    protected void configure() {
        TypeData<?> parentClassTypeData = null;
        Set<Class<?>> classes = buildHierarchy(type);
        Map<String, TypeParameterMap> propertyTypeParameterMap = new HashMap<>();

        List<Class<?>> classesArray = new ArrayList<Class<?>>(classes);
        Collections.reverse(classesArray);

        List<Annotation> annotations = new ArrayList<>();
        for (Class<?> klass : classesArray) {
            List<String> genericTypeNames = processTypeNames(klass);

            annotations.addAll(List.of(klass.getDeclaredAnnotations()));

            processFields(klass, parentClassTypeData, genericTypeNames, propertyTypeParameterMap);

            parentClassTypeData = TypeData.newInstance(klass.getGenericSuperclass(), klass);
        }
        annotations(annotations);
    }

and my testcase in the dev.morphia.test.TestMapping looks like

    @Test
    public void testRecursiveGeneric() {
        getMapper().map(SpecificEntity.class);

        SpecificEntity beforeDb = new SpecificEntity();
        beforeDb.setId(UUID.randomUUID());
        beforeDb.setTest(UUID.randomUUID());
        beforeDb.setTest2(UUID.randomUUID());

        getDs().save(beforeDb);
        SpecificEntity fromDB = getDs().find(SpecificEntity.class).filter(Filters.eq("_id", beforeDb.getId()))
                .iterator().next();

        assertEquals(beforeDb.getId(), fromDB.getId());
        assertEquals(beforeDb.getTest(), fromDB.getTest());
        assertEquals(beforeDb.getTest2(), fromDB.getTest2());
    }

    @Entity
    public static class GenericEntity<T> {
        @Id
        protected T id;
        protected T test;
        protected UUID test2;

        public T getId() {
            return id;
        }

        public void setId(T id) {
            this.id = id;
        }

        public T getTest() {
            return test;
        }

        public void setTest(T test) {
            this.test = test;
        }

        public UUID getTest2() {
            return test2;
        }

        public void setTest2(UUID test2) {
            this.test2 = test2;
        }
    }

    @Entity
    public static class SpecificEntity extends GenericEntity<UUID> {

    }
0reactions
evanchoolycommented, Sep 9, 2020

That is, more or less, what I’d discovered last night, too, before I was too tired to finish testing. 😃 Nice work.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Java Generics: How to specify a Class type ... - Stack Overflow
I am trying to write a utility method which accepts a class reference Class<T> and populates a map of type Map<String, T> (accepts...
Read more >
Mapping a generic class to a nongeneric class - IBM
It is quite common to map a generic class to another generic class. However, in certain cases, you must map a generic class...
Read more >
Java Generics Example Tutorial - Generic Method, Class ...
Now the problem with above implementation is that it won't work with List of Integers or Doubles because we know that List<Integer> and...
Read more >
Open Generics - AutoMapper documentation
AutoMapper will skip open generic type maps during configuration validation, since you can still create closed types that don't convert, such as Source<Foo>...
Read more >
Generics: in, out, where - Kotlin
Instead, Kotlin has declaration-site variance and type projections. Let's think about why Java needs these mysterious wildcards. The problem ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found