Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a @MappedSuperclass equivalent annotation for mongoDB in spring?

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
}
like image 429
Sumit Kripalani Avatar asked Oct 16 '25 02:10

Sumit Kripalani


1 Answers

You do not need any annotation to do that in Mongo. Mongo itself will take care of superclass for you.

Just extend BaseEntity class in all your entities, all entities will have fields from BaseEntity class when you read and write entities to database. This also works at multilevel hierarchy. i.e. Post extends BaseEntity, BaseEntity extends Entity, in this case Post will have fields from both BaseEntity and Entity class.

like image 58
Harshit Avatar answered Oct 17 '25 15:10

Harshit