Spring Data Mongodb Repositories don't implement inheritance correctly

允我心安 提交于 2019-11-30 18:52:13

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!