Spring Data Mongodb - repository for collection with different types

后端 未结 2 1311
傲寒
傲寒 2021-01-02 17:34

I have a mongo collection that may contain three types of entities that I map to java types:

  • Node
  • LeafType1
  • LeafType2

Collecti

2条回答
  •  没有蜡笔的小新
    2021-01-02 18:02

    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 { }
    

    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:

    Entity:

    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;
        ...
    

    Repository:

    public interface DocumentDao extends MongoRepository{
    ...
    

    And, if your documents in mongodb collection does not have the "_class" property. You can use Converter:

    When storing and querying your objects it is convenient to have a MongoConverter instance handle the mapping of all Java types to DBObjects. However, sometimes you may want the `MongoConverter’s do most of the work but allow you to selectively handle the conversion for a particular type or to optimize performance.

提交回复
热议问题