Priyamal
Priyamal

Reputation: 2969

How to use Java inheritance in Jpa Entities

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?

Upvotes: 6

Views: 6403

Answers (2)

Karthik R
Karthik R

Reputation: 5786

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.

Upvotes: 7

Serg Vasylchak
Serg Vasylchak

Reputation: 874

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

Upvotes: 5

Related Questions