Careeroza
MappedSuperclass
Sharing Fields, Not Tables
Many entities share fields: id, audit columns, maybe a version. A @MappedSuperclass is a parent class whose fields are copied into each child's table. It is not an entity itself: no table, no repository, no polymorphic queries.
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@CreatedDate @Column(updatable = false) private Instant createdAt;
@LastModifiedDate private Instant updatedAt;
public Long getId() { return id; }
}
@Entity @Table(name = "products") public class Product extends BaseEntity { private String name; ... }
@Entity @Table(name = "categories") public class Category extends BaseEntity { private String name; }create table products (id bigint not null auto_increment, created_at datetime(6), updated_at datetime(6), name varchar(255), ..., primary key (id));
create table categories (id bigint not null auto_increment, created_at datetime(6), updated_at datetime(6), name varchar(255), primary key (id));MappedSuperclass vs Entity Inheritance
@MappedSuperclass | @Entity + @Inheritance | |
|---|---|---|
| Parent has a table | no | depends on strategy |
Query the parent (select p from Payment p) | no | yes, polymorphic |
| Association to the parent type | no | yes (@OneToOne Payment payment) |
| Use for | technical fields (id, audit, version) | real "is-a" domain types |