Spring中的mongoDB是否有@MappedSuperclass等效注释?

Sum*_*ani 3 java mongodb spring-data-jpa spring-data-mongodb spring-boot

在我的项目中,我们正在一定程度上从 SQL 转向 NoSQL。我想知道,我们如何将 BaseClass 属性继承到 spring data mongo 中的子类中。我知道如何在 Spring JPA for SQL 中执行此操作。

例如,下面是 BaseEntity 父类,它用 @MappedSuperClass 注释它有 id 和 version 作为其字段。

@MappedSuperclass
public class BaseEntity {
 
    @Id
    @GeneratedValue
    private Long id;
 
    @Version
    private Integer version;
 
    //Getters and setters omitted for brevity
}
Run Code Online (Sandbox Code Playgroud)

实体可以扩展 BaseEntity 类并跳过声明 @Id 或 @Version 属性,因为它们是从基类继承的。

@Entity(name = "Post")
@Table(name = "post")
public class Post extends BaseEntity {
 
    private String title;
 
    @OneToMany
    private List comments = new ArrayList();
 
    @OneToOne
    private PostDetails details;
 
    @ManyToMany
    @JoinTable(//Some join table)
    private Set tags = new HashSet();
 
    //Getters and setters omitted for brevity
 
    public void addComment(PostComment comment) {
        comments.add(comment);
        comment.setPost(this);
    }
 
    public void addDetails(PostDetails details) {
        this.details = details;
        details.setPost(this);
    }
 
    public void removeDetails() {
        this.details.setPost(null);
        this.details = null;
    }
}
Run Code Online (Sandbox Code Playgroud)
@Entity(name = "PostComment")
@Table(name = "post_comment")
public class PostComment extends BaseEntity {
 
    @ManyToOne(fetch = FetchType.LAZY)
    private Post post;
 
    private String review;
 
    //Getters and setters omitted for brevity
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能在 Mongo 中实现同样的事情?例如

@MappedSuperclass
public class BaseEntity {
 
    @Id
    @GeneratedValue
    private Long id;
 
    @Version
    private Integer version;
 
    //Getters and setters omitted for brevity
}
Run Code Online (Sandbox Code Playgroud)
@Document(collection = "Post")
public class Post extends BaseEntity {
 
    private String title;
 
    //Rest of the code
}
Run Code Online (Sandbox Code Playgroud)
@Document(collection = "PostComment")
public class PostComment extends BaseEntity {
 
    @ManyToOne(fetch = FetchType.LAZY)
    private Post post;
 
    private String review;
 
    //Getters and setters omitted for brevity
}
Run Code Online (Sandbox Code Playgroud)

Har*_*hit 6

在 Mongo 中不需要任何注释即可执行此操作。Mongo 本身会为你处理超类。

只需在所有实体中扩展 BaseEntity 类,当您向数据库读取和写入实体时,所有实体都将具有 BaseEntity 类中的字段。这也适用于多级层次结构。即Post extends BaseEntityBaseEntity extends Entity在这种情况下,Post 将具有来自 BaseEntity 和 Entity 类的字段。