spring-boot-starter-data-mongodb Map enum to String in the entity

Viewed 576

I have an entity:

@Document(collection = "test")
public class Test{

    @Id
    @Field("_id")
    private String id;

    @Field("type")
    private Type type;

...

}

it is enum:

public enum Type {
    ONE("one"), TWO("two"), THREE("three");

    private final String name;

    Type (String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

But mongo collection has a String type of "type" field. How can I convert my enum to String?

findAllByType(Type type);
1 Answers

Spring Data MongoDB takes care of conversion from enum to String type. Just below code is enough to achieve your requirement.

public interface TestRepository extends MongoRepository<Test, String> {
    List<Test> findAllByType(Type type);
}

Given your enum class, you ensure that your collection contains the type field values in CAPS i.e., "ONE", "TWO", "THREE" etc., not as "one", "two", "three" etc. If it is not in CAPS, your query might not return anything.

Related