In my project, we are moving from SQL to NoSQL to a certain extent. I wanted to know, how can we inherit BaseClass properties into child classes in spring data mongo. I know how to do it in Spring JPA for SQL.
Example, Below is BaseEntity parent class which is annotated with @MappedSuperClass It has id and version as its fields.
@MappedSuperclass
public class BaseEntity {
@Id
@GeneratedValue
private Long id;
@Version
private Integer version;
//Getters and setters omitted for brevity
}
entities can extend the BaseEntity class and skip declaring the @Id or @Version properties since they are inherited from the base class.
@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
}
How can I implement same thing in Mongo? For example
@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
}