Home > Mobile >  I want to implement inheritance strategy(TABLE_PER_CLASS) using discriminator column
I want to implement inheritance strategy(TABLE_PER_CLASS) using discriminator column

Time:04-05

Is that Possible to use discriminator with strategy = InheritanceType.TABLE_PER_CLASS?

@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@DiscriminatorColumn(
        name = "TYPE",
        discriminatorType = DiscriminatorType.STRING
)

abstract class BaseEntity {

    @Id

    @GeneratedValue(strategy = GenerationType.AUTO)

    @Column(name = “id”, updatable = false, nullable = false)

    protected Long id;

}

@DiscriminatorValue("employee")
class Employee extends BaseEntity {
    //contains different columns
}

@DiscriminatorValue("audit")
class Audit extends BaseEntity {
    //contains different columns`
}

How to access data from BaseEntity based on discriminatorValue as "employee" or "audit"?`

CodePudding user response:

To retrieve employees or audits you need to namedQueries :

@NamedQueries(name="Employee.findAll", query="select e from employee e")
@Entity
@DiscriminatorValue("employee")
class Employee extends BaseEntity {
  //stuff
}

@NamedQueries(name="Audit.findAll", query="select a from audit a")
@Entity
@DiscriminatorValue("audit")
class Audit extends BaseEntity {
  //stuff
}

and then you fetch them like this :

EntityManager em;
List<BaseEntity> list = new ArrayList<>();
list.addAll(em.createNamedQuery("Employee.findAll", Employee.class)
.getResultList());
list.addAll(em.createNamedQuery("Audit.findAll", Audit.class)
.getResultList());

CodePudding user response:

JPA has the 'TYPE' function that works to filter on the class type. An example from the specification is:

"SELECT e FROM Employee e WHERE TYPE(e) IN (Exempt, Contractor)"

Executing this will return only Exempt and Contractor instances.

In your case though, I don't see why Employee and Audit extend the same BaseEntity or how a single table would hold rows for each, as the properties seem extremely different. If you must/want to query BaseEntity for select properties from an Employee and select properties from Audit, you'll need to use casting. This is accessible in JPA via the 'TREAT' function, with an example from the spec given as:

"SELECT e FROM Employee e
  WHERE TREAT(e AS Exempt).vacationDays > 10
      OR TREAT(e AS Contractor).hours > 100"
  • Related