JPA use two Entity classes for the same table using inheritance

Normally with JPA you’re creating one entity per one database table, what if you want to separate the entities using Java inheritance but using the same table? For example: Both StaffUser and NormalUser of a website are just User, they should be in the same table but for convenience on the data model and programming, how to separate them as illustrate below?

Luckily JPA already have @DiscriminatorColumn which can be used to differentiate between the derived entities, and both of these entities extends from the same abstractEntity which in tern mapped to one single table.

import lombok.Data;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;

@Entity
@Table(name = "users")
@EntityListeners(AuditingEntityListener.class)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Data
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
public abstract class AbstractUser {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    private String firstName;
    private String lastName;
    private String age;
    private String email;
    private String password;
}

As can be seen, the above abstract class is mapped to one table users and have a discriminator column called “type”, this column determines the child entity as following:

import lombok.Data;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

@Entity
@DiscriminatorValue("NORMAL")
@Data
public class NormalUser extends AbstractUser {
    private String facebookId;
    private String topic;
}
import lombok.Data;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

@Entity
@DiscriminatorValue("STAFF")
@Data
public class StaffUser extends AbstractUser {
    private Long managerId;
    private String permissions;
}

Both NormallUser and StaffUser classes will now have all the properties declared in AbstractUser, both of them will be stored in the same table users but on the code module side, they are two different entities, forming from two different Java classes.

Add to my src(0)

No account yet? Register