Search code examples
jpaeclipselinksingle-table-inheritance

JPA Inheritance :mapping derived entities to different tables


I use SINGLE_TABLE inheritance startegy to map my usres (see code example bellow).

Is there a way to map UnActiveRegularUser and UnActiveBusinessUser from "ACTIVE_USERS" table to another table, for example "UNACTIVE_USERS" and keep the inheritance startegy?

Note:

-The point here is to avoid code duplication between ex. RegularUser Vs UnActiveRegularUser (since they use the same properties) but still to map them to 2 different tables: "ACTIVE_USERS" and "UNACTIVE_USERS".

-strategy = InheritanceType.SINGLE_TABLE should not be changed.

-May adding another abstraction layer solve this problem?

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = "ACTIVE_USERS")
public class User {
    @Id @GeneratedValue
    protected Long id;

    @Column(nullable = false)
    protected String name;
}


@Entity
public class RegularUser extends User{
//more getters and settres
}

@Entity
public class UnActiveRegularUser extends User{
//same getters and setters as in RegularUser
}

@Entity
public class BusinessUser extends User {
//more getters and settres
}

@Entity
public class UnActiveBusinessUser extends User {
//same getters and setters as in BusinessUser
}

Thanks, Nathan


Solution

  • Persisting fields to another table won't prevent code duplication. I think you should just make UnActiveBusinessUser extend BusinessUser, and UnactiveRegularUser extend RegularUser.

    Note that if a user can become unactive (i.e. it is a RegularUser and becomes an UnactiveRegularUser), inheritance is not the right solution: an object can't go from one type to another. Since it seems UnactiveRegularUser doesn't have anything more than RegularUser, I'm not sure this subclass is useful.