将通用对象与 Spring 数据 Mongo 一起使用
Using generic objects with Spring Data Mongo
我正在使用 Spring 数据 Mongo 将我的程序与 MongoDB 的实例连接起来。我在 Mongo 中存储了一个类似于以下的类型。
@Document
class A<T> {
@Id String id;
Instant createdAt;
List<T> values;
}
如您所见,在主文档中的 属性 中使用了泛型类型 T
。我在使用查询提取此类文档时遇到了一些问题。我目前正在使用类似于以下语句的内容。
List<A> list =
mongoTemplate.find(Query.query(Criteria.where("id").in("id1", "id2"),
A.class,
"collectionName");
不幸的是,上面的代码不提供对通用字段的任何支持。我查看了文档和 MongoTemplate
的代码,但我没有找到任何东西。
其他 模板 类 of Spring 提供此支持。以 RestTemplate
为例。 exchange
方法的许多签名使用 ParameterizedTypeReference<T>
来实现与我正在搜索的 MongoTemplate
类似的东西(例如 this)。
在我看来,在 MongoTemplate
中也有类似的东西会很有用。
有没有办法在提取过程中处理通用类型?
谢谢。
我认为没有办法支持具有 Spring 数据 MongoDB 的通用文档。
Oliver Gierke 在他的评论中明确解释道:
Without a subtype of A<T>
that binds T
to some type, there's no point in even using a generic type here. You could just stick to List<Object>
.
实现您需要的最好方法是为每个 values
类型创建一个 A
的子类型。像这样:
@Document
public class StringA extends A<String> { ... }
@Document
public class IntegerA extends A<Integer> { ... }
我正在使用 Spring 数据 Mongo 将我的程序与 MongoDB 的实例连接起来。我在 Mongo 中存储了一个类似于以下的类型。
@Document
class A<T> {
@Id String id;
Instant createdAt;
List<T> values;
}
如您所见,在主文档中的 属性 中使用了泛型类型 T
。我在使用查询提取此类文档时遇到了一些问题。我目前正在使用类似于以下语句的内容。
List<A> list =
mongoTemplate.find(Query.query(Criteria.where("id").in("id1", "id2"),
A.class,
"collectionName");
不幸的是,上面的代码不提供对通用字段的任何支持。我查看了文档和 MongoTemplate
的代码,但我没有找到任何东西。
其他 模板 类 of Spring 提供此支持。以 RestTemplate
为例。 exchange
方法的许多签名使用 ParameterizedTypeReference<T>
来实现与我正在搜索的 MongoTemplate
类似的东西(例如 this)。
在我看来,在 MongoTemplate
中也有类似的东西会很有用。
有没有办法在提取过程中处理通用类型?
谢谢。
我认为没有办法支持具有 Spring 数据 MongoDB 的通用文档。
Oliver Gierke 在他的评论中明确解释道:
Without a subtype of
A<T>
that bindsT
to some type, there's no point in even using a generic type here. You could just stick toList<Object>
.
实现您需要的最好方法是为每个 values
类型创建一个 A
的子类型。像这样:
@Document
public class StringA extends A<String> { ... }
@Document
public class IntegerA extends A<Integer> { ... }