DEV Community

Said Olano
Said Olano

Posted on

How does the @MappedSuperclass Hibernate annotation work?

The annotation @MappedSuperclass is part of JPA (not exclusive to Hibernate).
It is used to mark a base class that is not an entity in its own right, but whose properties are inherited by child entities.

import javax.persistence.MappedSuperclass;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@MappedSuperclass
public abstract class BaseEntity {

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

    private String createdBy;
    private String updatedBy;

    // getters and setters
}

Enter fullscreen mode Exit fullscreen mode

And a child entity:

import javax.persistence.Entity;

@Entity
public class User extends BaseEntity {
    private String username;
    private String email;

    // getters and setters
}
Enter fullscreen mode Exit fullscreen mode

Here is the result:

Top comments (0)