Home » Java » java – Enums as key of a Map with DBref with spring data mongo-Exceptionshub

java – Enums as key of a Map with DBref with spring data mongo-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment


I am trying to save and retrieve documents mapped to a class into Mongodb using spring data mongodb with a map field.

Here is a simplified version of my objects in java :
An enum :

public enum MyEnum {

And an entity to be persisted :

public class Entity {

  private Map<MyEnum, MySubEntity> mapField;

  public Entity(Map<MyEnum, MySubEntity> mapField){
      this.mapField = mapField;

I have a simple Repository to save entities and retrieve them. After a save, the document is correctly created in MongoDB.

The problem occur when I try to retrieve it. The object Entity is created and returned by the repository, but any attempt to access or use the mapField field will fail with the error : "java.lang.String cannot be cast to MyEnum"
When using java debugguer to spy on the retrieved Entity object, the mapField field seems to have String as keys as opposed to MyEnum.

I have tried unsuccesfully to register a custom converter for this type.

My question is : is there anything I can do to match my use case, or is my model just not supported by spring data mongodb and I should alter it?

Update :

The problem seems to be related to the use of @DBRef on the map. I have tried without it and the Entity is retrieved correctly. Not sure why this is…

How to&Answers:

You are right. Keys in MongoDb should be String type. You can create converter to convert your keys to String type before adding to database.Using toString() method to your key could be a solution.

Here is a good explanation and probably the answer to your question .