【发布时间】:2021-02-06 06:31:50
【问题描述】:
在我的项目中,我们在一定程度上正在从 SQL 转向 NoSQL。 我想知道,我们如何将 BaseClass 属性继承到 spring data mongo 中的子类中。 我知道如何在 Spring JPA for SQL 中做到这一点。
例如, 下面是用 @MappedSuperClass 注释的 BaseEntity 父类 它的字段为 id 和 version。
@MappedSuperclass
public class BaseEntity {
@Id
@GeneratedValue
private Long id;
@Version
private Integer version;
//Getters and setters omitted for brevity
}
实体可以扩展 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;
}
}
@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
}
如何在 Mongo 中实现相同的功能?例如
@MappedSuperclass
public class BaseEntity {
@Id
@GeneratedValue
private Long id;
@Version
private Integer version;
//Getters and setters omitted for brevity
}
@Document(collection = "Post")
public class Post extends BaseEntity {
private String title;
//Rest of the code
}
@Document(collection = "PostComment")
public class PostComment extends BaseEntity {
@ManyToOne(fetch = FetchType.LAZY)
private Post post;
private String review;
//Getters and setters omitted for brevity
}
【问题讨论】:
标签: java mongodb spring-boot spring-data-jpa spring-data-mongodb