How to inherit properties from a base class entity using @MappedSuperclass with JPA and Hibernate

Imagine having a tool that can automatically detect if you are using JPA and Hibernate properly. Hypersistence Optimizer is that tool!

Introduction

Last week, one of my blog readers asked me of a way to reuse the @Id mapping so that it won’t have to be declared on each an every entity.

Because this is a good opportunity to introduce @MappedSuperclass, I decided to answer the question with a blog post.

Domain Model

Assuming we are using MySQL and we have the following tables:

MappedSuperclass MySQL tables

As I already explained, it’s a really bad idea to use the GenerationType.AUTO identifier strategy with MySQL because it falls back to using the sequence-like TABLE generator which scales badly.

So, even if the IDENTITY strategy prevents Hibernate from using JDBC batch inserts, it’s still a much better alternative to the TABLE identifier generation strategy.

However, we don’t want to declare the @Id on every entity (e.g. Post, PostDetails, PostComment, Tag), so let’s see how we can address this issue.

@MappedSuperclass

The JPA standard specification defines the @MappedSuperclass annotation to allow an entity to inherit properties from a base class.

Unlike the @Inheritance annotation which maps the Java Object inheritance to a relational database model which emulates inheritance, @MappedSuperclass only models inheritance in the OOP world.

From a database perspective, the @MappedSuperclass inheritance model is invisible since all the base class properties are simply copied to the database table mapped by the actual entity class.

Therefore, we can define the following BaseEntity base class:

@MappedSuperclass
public class BaseEntity {

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

    @Version
    private Integer version;

    //Getters and setters omitted for brevity
}

Now, our entities can extend the BasedEntity class and skip declaring the @Id or @Version properties since they are inherited from the base class. If the BaseEntity were not annotated with @MappedSuperclass, the @Id or @Version properties would not be inherited by the classes extending BasedEntity.

Post entity

@Entity(name = "Post")
@Table(name = "post")
public class Post extends BaseEntity {

    private String title;

    @OneToMany(
        mappedBy = "post",
        cascade = CascadeType.ALL,
        orphanRemoval = true
    )
    private List comments = new ArrayList();

    @OneToOne(
        mappedBy = "post",
        cascade = CascadeType.ALL,
        orphanRemoval = true,
        fetch = FetchType.LAZY
    )
    private PostDetails details;

    @ManyToMany
    @JoinTable(
        name = "post_tag",
        joinColumns = @JoinColumn(name = "post_id"),
        inverseJoinColumns = @JoinColumn(name = "tag_id")
    )
    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;
    }
}

Note that we are using mappedBy @OneToMany associations because this is the best way to map this type of relationship.

Also, the @ManyToMany association uses Set instead of List because that’s going to yield more efficient queries for this type of relationship.

PostComment entity

@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
}

Note that we are using FetchType.LAZY because, by default, @ManyToOne associations are fetched eagerly, and that’s bad for performance.

PostDetails entity

@Entity(name = "PostDetails")
@Table(name = "post_details")
public class PostDetails extends BaseEntity {

    @Column(name = "created_on")
    private Date createdOn;

    @Column(name = "created_by")
    private String createdBy;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private Post post;

    //Getters and setters omitted for brevity
}

Note that we are using @MapsId which is the best way to map a @OneToOne association.

Also, we are using FetchType.LAZY because, by default, @OneToOne associations are fetched eagerly, and that’s bad for performance.

Tag entity

@Entity(name = "Tag")
@Table(name = "tag")
public class Tag extends BaseEntity {

    @NaturalId
    private String name;

    //Getters and setters omitted for brevity
}

Note the use of the @NaturalId annotation which allows you to map a business key and fetch the Tag entity by its natural identifier.

Testing time

Now, when creating two Tag entities:

Tag jdbc = new Tag();
jdbc.setName("JDBC");

entityManager.persist(jdbc);

Tag hibernate = new Tag();
hibernate.setName("Hibernate");

entityManager.persist(hibernate);

Hibernate generates the following queries:

INSERT INTO tag (version, name) 
VALUES (0, 'JDBC')

INSERT INTO tag (version, name) 
VALUES (0, 'Hibernate')

Note that the version property is set because it’s inherited from the BaseEntity class.

We don’t need to provide the @Id because the IDENTITY strategy generates the entity identifier upon persisting the entity.

When saving a Post and its associated PostDetails entity:

Post post = new Post();
post.setTitle("High-Performance Java Persistence");

PostDetails postDetails = new PostDetails();
postDetails.setCreatedBy("Vlad Mihalcea");
postDetails.setCreatedOn(new Date());
post.addDetails(postDetails);

Session session = entityManager.unwrap(Session.class);

post.getTags().add(
    session
    .bySimpleNaturalId(Tag.class)
    .getReference("jdbc")
);
post.getTags().add(
    session
    .bySimpleNaturalId(Tag.class)
    .getReference("hibernate")
);

entityManager.persist(post);

Hibernate generates the following queries:

INSERT INTO post (version, title) 
VALUES (0, 'High-Performance Java Persistence')

INSERT INTO post_details (version, created_by, created_on, id) 
VALUES (0, 'Vlad Mihalcea', '2017-11-08 12:29:23.498', 1)

INSERT INTO post_tag (post_id, tag_id) 
values (1, 2)

INSERT INTO post_tag (post_id, tag_id) 
values (1, 1)

When saving a PostComment entity:

Post post = entityManager.createQuery(
    "select p " +
    "from Post p " +
    "where p.title = :title", Post.class)
.setParameter("title", "High-Performance Java Persistence")
.getSingleResult();

PostComment postComment = new PostComment();
postComment.setReview("THE book on Hibernate");

post.addComment(postComment);

Hibernate generates the following queries:

INSERT INTO post_comment (version, post_id, review) 
VALUES (0, 1, 'THE book on Hibernate')

If you enjoyed this article, I bet you are going to love my Book and Video Courses as well.

Seize the deal! 50% discount. Seize the deal! 50% discount.

Conclusion

So, every time you need to inherit properties from a base class, you need the @MappedSuperclass annotation. Otherwise, JPA entities will ignore the base class properties even if your entity extends a given base class.

FREE EBOOK

15 Comments on “How to inherit properties from a base class entity using @MappedSuperclass with JPA and Hibernate

  1. The hibernate-jpamodelgen will not work well with MappedSuperClasses coming from an external jar. They have to be in the same package.

    • Sounds like a bug. You should create a Jira issue for it.

  2. Hi Vlad,

    What is the bast way to inherit OneToMany relationship from a base class?

    I need to add a scalable solution where some of my entities declare the same collection. I don’t want to create one collection table for each main entity that has the same type of collection.

    My scenario is a bit complex, but to put in simple terms, imagine I have Person and Company, both can have multiple contact phone information so I want each to have a collection of Phone. Ideally, I want only one table to hold phones. In this case, shouldn’t the phone table contain a owner_type column to identity what actual child class is the owner of this phone? How to I declare this using JPA annotations? Is there a way to to this using @ElementCollection/@Embeddable in a @MapperSuperclass?

      • So, I just read chapter section 11.4 Mapped superclass, and my conclusion is that what I’m looking for is not possible. The last sentence, just before chapter 12 (flushing) says @MappedSuperclass cannot have @OneToMany. Did I understand correctly? Any chance of achieving that with @ElementCollection/@Embeddable? I wanted to avoid multiple phone tables (one for each entity), similar to the topic_statistics in the books scenario.

      • Why would you assume that? Show me the paragraph that says that.

      • “Polymorphic queries against the Topic class are not permitted and the Board entity cannot
        define a @OneToMany Topic collection either.”

      • Yes, that’s correct. However, you asked about adding a collection association to the @MappedSuperclass, which is supported since the association is pushed to the owning entity.

      • Thanks, I’ll try to create a sample project on github to better illustrate the problem.

  3. Is there any way to ignore some inherited properties from @MappedSuperclass with JPA and Hibernate?

    • Try making it @Transient and see if you can override it in the entity class as a persistent property.

      • I want it other way, i.e. since most of the classes are using properties from @MappedSuperclass but there are very few classes/class, which doesn’t want some properties to be persisted. So by default the field should be non transient and if any subclass wants it to be transient, it should be possible. Is there way for this?

      • That’s not possible. Use two separate MappedSuperclass mappings for that. One without the property as the first base class. The other extending the first and declaring the property. Then you extend either one or the other in your actual entities.

  4. Hi Vlad

    I’ve used the @MappedSuperClass to create a BaseEntity similar to the one in this post for a Spring Boot JPA application. I have also created an Entity object which inherits the BaseEntity. When I run a JUnit testing using H2, the table generated has two id columns, one named “id” and one named “rate_id”. “rate_id” is set as the primary key and “id” is just another not nullable field. This issue is similar to this JIRA – https://hibernate.atlassian.net/browse/JPA-16.

    I wanted to know why this happens.

    Regards
    Varghese Paul

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.