Ask Your Question
3

In Spring boot and MONGO, how can one utilize the Inheritance concept to include a parent class based on shared parameters, without referencing the document?

asked 2021-08-08 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-11-12 22:00:00 +0000

lalupa gravatar image

In Spring Boot and MongoDB, one can utilize the inheritance concept by creating a parent class that includes shared parameters and then extending it to child classes. To do this, one can use the @InheritAnnotations annotation along with the @Document annotation for defining the parent class as a MongoDB document.

For example, consider the following parent class:

@InheritAnnotations
@Document(collection = "products")
public class Product {
    @Id
    protected String id;
    protected String name;
    protected String description;

    // constructors, getters and setters
}

This parent class defines a MongoDB document named "products" and includes shared parameters such as id, name, and description that can be used in child classes. Here's an example of a child class that extends the Product class:

@Document(collection = "books")
public class Book extends Product {
    protected String author;
    protected int pages;

    // constructors, getters and setters
}

As you can see, the Book class extends the Product class and includes additional parameters such as author and pages. However, it does not reference the "products" document since it inherits the collection from the parent class.

By using inheritance in this way, one can avoid duplication of code and ensure consistency of shared parameters across multiple classes.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-08-08 11:00:00 +0000

Seen: 12 times

Last updated: Nov 12 '21