gpt4 book ai didi

spring-boot-starter-data-mongodb 将枚举映射到实体中的字符串

转载 作者:行者123 更新时间:2023-12-05 06:59:36 26 4
gpt4 key购买 nike

我有一个实体:

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

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

@Field("type")
private Type type;

...

}

它是枚举:

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

private final String name;

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

public String getName() {
return name;
}
}

但是mongo集合有一个String类型的“type”字段。如何将我的枚举转换为字符串?

findAllByType(Type type);

最佳答案

Spring Data MongoDB 负责从enumString 类型的转换。下面的代码足以满足您的要求。

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

给定您的enum 类,您确保您的集合包含 CAPS 中的type 字段值,即“ONE”、“TWO” , "THREE"等,而不是 "one"、"two"、"three"等。如果 不是大写,您的查询可能不会返回任何内容。

关于spring-boot-starter-data-mongodb 将枚举映射到实体中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64367755/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com