Video in progress

What is @MappedSuperclass and how does it differ from inheritance with @Entity?

@MappedSuperclass is a parent class that collects common fields (id, createdAt, version) in one place. It has no table of its own and is not an entity. You can't query it or reference it; only its fields are copied into the subclasses' tables.

📖 Answer

@MappedSuperclass
public abstract class BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected Long id;

    @Column(nullable = false, updatable = false)
    protected Instant createdAt;

    @Version
    protected long version;

    @PrePersist
    void onCreate() { createdAt = Instant.now(); }
}

@Entity
public class Product extends BaseEntity {
    private String title;
}

The products table gets the columns id, created_at, version and title. There is no base_entity table.

How it differs from @Inheritance:

  • @MappedSuperclass is only code reuse. You can't write select b from BaseEntity b, and there is no @ManyToOne BaseEntity either;
  • @Entity + @Inheritance is real polymorphism: you can query and associate by the parent type.

In practice almost every project has a single BaseEntity or AuditableEntity. Just don't pile extra things into it. A field that not every entity needs shouldn't live there.