4

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.

2
  • 1
    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>. It's generally pretty unclear what you're asking: what do you actually want to achieve? What do the documents look like you want to query? What result do you get and what about the result do you expect to be different? Commented Oct 5, 2017 at 10:44
  • @OliverGierke I updated my question. I apologize if the question hurt you in any way. It was not my intention. Commented Oct 5, 2017 at 12:00

1 Answer 1

5

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 binds T to some type, there's no point in even using a generic type here. You could just stick to List<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> { ... }
Sign up to request clarification or add additional context in comments.

1 Comment

"I don't think there is a way to support generic documents with Spring Data MongoDB." is a broad statement. Especially in the light of not even knowing what "support generic documents" is supposed to mean. See my comment to the original question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.