Search code examples
hibernatejpahqljpa-2.0jpql

JPQL HQL query operating on top of class hierarchy with joined inheritance strategy and applying DTO projection


Given I have following class hierarchy with joined inheritance strategy:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Notification {

    protected Long id;
    protected Long code;

    protected Notification() {
    }
}

@Entity
@PrimaryKeyJoinColumn(name = "NOTIFICATION_ID")
public class Sms extends Notification {

    private String phoneNumber;
    private String smsText;

    public Sms() {
    }
}

@Entity
@PrimaryKeyJoinColumn(name = "NOTIFICATION_ID")
public class Push extends Notification {

    private String application;
    private String pushText;
    
    public Push() {
    }
}

How can I write JPQL / HQL query which will return List<NotificationDetails> where NotificationDetails is:

public class NotificationDetails {

    private final String contact;
    private final String content;

    public NotificationDetails(String contact, String content) {
        this.contact = contact;
        this.content = content;
    }
}

where mapping should be as follows:

contact - phoneNumber / application
content - smsText / pushText

Solution

  • Hibernate has support for something called implicit subtype property resolving, so you can use a query like the following:

    List<NotificationDetails> results = em.createQuery(
       "select new com.your.entities.NotificationDetails(coalesce(n.phoneNumber, n.application),  coalesce(n.smsText, n.pushText)) from Notification n ",
       NotificationDetails.class
    ).getResultList();