Spring Data Mongodb Repositories don't implement inheritance correctly

前端 未结 1 1415
予麋鹿
予麋鹿 2021-01-04 12:19

Having two types of entities, that are mapped to two Java classes in the single MongoDB collection:

@Document
public class Superclass { ... }

@Document(coll         


        
相关标签:
1条回答
  • 2021-01-04 13:06

    I encounter the same issue.

    Take a look at the source code and at my surprise it is kind of not implemented. It adds the Collection name and the entity class but not inserted in the final query the _class property. And after taking a look at it I realized that how Mongo would know that SubClass1 or Subclass2 derived from SuperClass. So I just override the SimpleMongoRepository Class and create my own Factory that put that class instead of the default SimpleMongoRepository

    Here what i added:

    public MySimpleMongoRepository(MongoEntityInformation<T, ID> metadata, MongoOperations mongoOperations) {
    
        Assert.notNull(mongoOperations);
        Assert.notNull(metadata);
    
        this.entityInformation = metadata;
        this.mongoOperations = mongoOperations;
        Reflections reflections = new Reflections("com.cre8techlabs.entity");
        Set<String> subTypes = reflections.getSubTypesOf(entityInformation.getJavaType()).stream().map(Class::getName).collect(Collectors.toSet());
        subTypes.add(entityInformation.getJavaType().getName());
        this.baseClassQuery = Criteria.where("_class").in(subTypes.toArray());
    }
    

    And here an example of implementation of a find

    public T findOne(ID id) {
        Assert.notNull(id, "The given id must not be null!");
        Query q = getIdQuery(id).addCriteria(baseClassQuery);
    
        return mongoOperations.findOne(q, entityInformation.getJavaType(), entityInformation.getCollectionName());
    }
    

    It works for me, I am just afraid that it take a little longer

    0 讨论(0)
提交回复
热议问题