问题描述
我有一个mongo集合,其中可能包含我映射到Java类型的三种类型的实体:
I have a mongo collection that may contain three types of entities that I map to java types:
- 节点
- LeafType1
- LeafType2
使用父项中的子节点的dbRefs收集以存储树状结构.
Collection is ment to store tree-like structure using dbRefs of child nodes in parent entry.
我没有在Spring参考文档中找到有关主题的任何信息,所以我在这里问:是否可以使用Repository
机制处理可能包含不同类型对象的集合?
I didn't find any information about subject in Spring reference documentation so I'm asking here: Is there a way to use Repository
mechanism to work with collection that may contain different types of objects?
在一个集合中声明多个用于不同类型的存储库似乎不是一个好主意,因为我经常遇到这样的情况:查询的对象不是预期的类型,并且为抽象类创建一个所有可能的类型继承都不起作用的存储库
Declaring several repositories for different types in one collection seems like not very good idea because I always struggle with situations when queried object is not of expected type and creating one repository for abstract class that all possible types inherrit doesn't seems to work.
为了说明我的意思:
/**
* This seems not safe
*/
public interface NodeRepository extends MongoRepository<Node, String> { }
public interface LeafType1Repository extends MongoRepository<LeafType1, String> { }
public interface LeafType2Repository extends MongoRepository<LeafType2, String> { }
/**
* This doesn't work at all
*/
public interface MyCollectionRepository extends MongoRepository<AbstractMyCollectionNode, String> { }
推荐答案
如果Node \ LeafType1 \ LeafType2是AbstractMyCollectionNode的子类,那么事情就容易了.只需像编写时那样声明存储库:
If Node\LeafType1\LeafType2 are sub-classes of AbstractMyCollectionNode, then things will be easy. Just declare the repository like you write:
public interface MyCollectionRepository extends MongoRepository<AbstractMyCollectionNode, String> { }
我们已经在一个项目中做到了这一点,并且效果很好. Spring Data将在mongodb集合中的文档中添加一个名为"_class"的属性,以便可以指出要实例化的类.
We have done this in a project, and it works good. Spring Data will add an property named '_class' to the documents in mongodb collection, so that it can finger out which class to instantiate.
存储在一个集合中的文档可能有一些相似之处,也许您可以为它们提取一个通用类.
Documents that stored in one collection may have some similarity, maybe you can extract a generic class for them.
以下是从我们的一个项目中复制的一些代码:
Here are some code copied from one of our projects:
实体:
public abstract class Document {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
....
public class WebClipDocument extends Document {
private String digest;
...
存储库:
public interface DocumentDao extends MongoRepository<Document, String>{
...
并且,如果您在mongodb集合中的文档不具有"_class"属性.您可以使用转换器:
And, if your documents in mongodb collection does not have the "_class" property. You can use Converter:
这篇关于Spring Data Mongodb-用于收集不同类型的存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!