Yanick Nedderhoff
Yanick Nedderhoff

Reputation: 1234

How can I store to different collections with MongoRepository depending on type of generic in document

I am using Spring Boot 1.5.6. Especially, I am using Spring Boot Data MongoDB for the connection to MongoDB.

Assume I have this MongoRepository

public interface MyRepository1 extends MongoRepository<MyDocumentClass<MyResult1>, String> {
}

and a second one

public interface MyRepository2 extends MongoRepository<MyDocumentClass<MyResult2>, String> {
}

Then I have my document

@Document(collection = "collectionName")
public class MyDocumentClass<T extends AbstractResult> {

    private String myString;
    private int myInt;
    private List<T> results;

    public MyDocumentClass(String myString, int myInt, List<T> results) {
        this.myString = myString;
        this.myInt = myInt;
        this.results = results;
    }

    public String getMyString() {
        return myString;
    }

    public int getMyInt() {
        return myInt;
    }

    public List<T> getResults() {
        return results;
    }
}

And of course AbstractResult as well as MyResult1 and MyResult2 extending it.

Before, MyDocumentClass wasn't generic. Then the code worked fine. But now I want to choose a different collection name based on what T is in MyDocumentClass. Is that possible? If yes, how?

If have already found a way using MongoTemplates, but that is not what I am looking for here.

Upvotes: 1

Views: 1894

Answers (2)

Abhijit Sarkar
Abhijit Sarkar

Reputation: 24518

As you had found out, you can do it using MongoTemplate, but the question isn't how you'd do it; it's should you do it. I'd say no; Java is not C++ - MyDocumentClass<MyResult1> and MyDocumentClass<MyResult2> are not different things. Generics in Java is merely a compile time qualifier.

There are more than one ways to discriminate between MyResult1 and MyResult2 but the easiest is probably to add a type in MyDocumentClass. Something like:

public class MyDocumentClass {
    private String type = "MyResult1 or MyResult2";
}

Upvotes: 1

yamenk
yamenk

Reputation: 51738

You cannot do that because of java's Type erasure. Generics are only visible at compile type. Thus on runtime the JVM cannot differentiate between MyDocumentClass<MyResult1> and MyDocumentClass<MyResult2>.

You can however store these instances in the same MongoRepository<MyDocumentClass, String>.

Upvotes: 1

Related Questions