I am using Spring Data Mongo to interface my program with an instance of MongoDB. I store inside Mongo a type similar to the following.
@Document
class A<T> {
@Id String id;
Instant createdAt;
List<T> values;
}
As you can see, the generic type T is used in a property inside the main document. I have some problems in extracting such document using queries. I am currently using something similar to the following statement.
List<A> list =
mongoTemplate.find(Query.query(Criteria.where("id").in("id1", "id2"),
A.class,
"collectionName");
Unfortunately, the above code does not offer any support for generic fields. I looked at the documentation and at the code of MongoTemplate, but I did not find anything.
Some others templates classes of Spring offer this support. Take RestTemplate for example. There are many signatures of the exchange methods that use a ParameterizedTypeReference<T> to achieve something similar to what I am searching for MongoTemplate (this, for example).
In my opinion, it would be useful to have something similar also in MongoTemplate.
Is there a way to handle the generic type during the extraction process?
Thanks.
I don't think there is a way to support generic documents with Spring Data MongoDB.
As clearly explained by Oliver Gierke in his comment:
Without a subtype of
A<T>that bindsTto some type, there's no point in even using a generic type here. You could just stick toList<Object>.
The best way to achieve what you need is to creare a sub-type of A for every values-type. Something like this:
@Document
public class StringA extends A<String> { ... }
@Document
public class IntegerA extends A<Integer> { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With