6

I'm running into something odd with inheritance and mongodbrepositories.

I have the following:

`

@Document
public class Base {
    public String fieldA;
}

public class Derived extends Base {
    public String fieldB;
}

public interface DerivedRepository extends MongoRepository<Base, String> {
    List<Derived> findByFieldA(String fieldA);
}

`

When inserting i get

Inserting DBObject containing fields: [_class, _id, fieldA, fieldB ] in collection: base

When i do findByFieldA('some value') on the repository i get the following:

find using query: { "fieldA" : "some value" } fields: null for class: class Derived in collection: derived

Any idea what is going on here? And how can I fix this, either by saving it to the proper derived collection or by querying from the base collection.

Regards,

1 Answer 1

14

First, I would make Derived class as document since the parent is going to be shared among many implementations.

public class Base {
    public String fieldA;
}

@Document
public class Derived extends Base {
    public String fieldB;

    @Override
    public String toString() {
        return "{fieldA: " + getFieldA() + ", fieldB: " + fieldB + "}";
    }
}

Second, change the repository specification with the type of document (class marked as @Document) as:

public interface DerivedRepository extends MongoRepository<Derived, String> {
    List<Derived> findByFieldA(String fieldA);
    List<Derived> findByFieldB(String fieldB);
}

I added extra method findByFieldB(String fieldB) to explain more.

With these changes, you should be able to query either with fieldA or fieldB as below:

public class SpringBootMongoApplication {
    @Autowired
    private DerivedRepository derivedRepository;

    public void testMethod() throws Exception {
        Derived derived1 = new Derived();
        derived1.setFieldB("fieldB1");
        derived1.setFieldA("fieldA1");

        Derived derived2 = new Derived();
        derived2.setFieldB("fieldB2");
        derived2.setFieldA("fieldA2");
        this.derivedRepository.save(Arrays.asList(derived1, derived2));

        List<Derived> deriveds = this.derivedRepository.findByFieldA("fieldA1");
        System.out.println(deriveds);

        List<Derived> deriveds1 = this.derivedRepository.findByFieldB("fieldB2");
        System.out.println(deriveds1);
    }
}

The output should be:

[{fieldA: fieldA1, fieldB: fieldB1}]
[{fieldA: fieldA2, fieldB: fieldB2}]

You can also verify the object persisted and their types with mongo query as below: enter image description here

I have created an Spring Boot sample app which you can find in Github.

Sign up to request clarification or add additional context in comments.

Comments

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.