6

I'm trying to create JPA entities by using inheritance , I am not using any JPA polymorphic mechanism to do this. The reason is I want model classes to be independent, so if I want to use JPA I can extend the same model classes and create JPA entities and get the job done. My question is, is this possible to achieve without using JPA polymorphic mechanism, because when I try to deal with the JPA entities created after extending the model classes I don't see the properties that are inherited from super class but I can see new properties in the table if I add new properties in to the extended JPA entity.

Here are my entities:

@Data
public abstract class AtricleEntity {

    protected Integer Id;
    protected String title;
    protected Integer status;
    protected String slug;
    protected Long views;
    protected BigDecimal rating;
    protected Date createdAt;
    protected Date updatedAt;
}


@Data
@Entity
@Table(name="articles_article")
@RequiredArgsConstructor
public class Article extends AtricleEntity {

    public static final String TABLE_NAME = "articles_article";

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer Id;

    private String title;
}



@Repository
public interface ArticleRepository extends JpaRepository<Article, Integer>{}

I can see a table with a column title created if i run this. that's because I've explicitly added that property in Article , but i want other columns to appear in the table with the help of java inheritance. is this possible?

2 Answers 2

7

Simple answer is NO. JPA cannot use object's inheritance out of the box coz of the simple reason that other children will have different column names and other parameters and might choose not even to save these columns.

So JPA has it's own inheritance mappings which an object might have to follow. Usage like MappedSuperclass might help. Reference : http://www.baeldung.com/hibernate-inheritance for hibernate.

Sign up to request clarification or add additional context in comments.

Comments

5

@MappedSuperclass annotation put on your super class should help. https://docs.oracle.com/javaee/5/api/javax/persistence/MappedSuperclass.html

1 Comment

But I wouldn`t suggest duplicating fields in child classes. Provide getters and setters of base fields in super class instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.