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:
@MappedSuperclassis only code reuse. You can't writeselect b from BaseEntity b, and there is no@ManyToOne BaseEntityeither;@Entity+@Inheritanceis 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.
Sign up to mark studied questions and save your progress.