微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JPQL HQL查询在类层次结构之上运行,具有连接的继承策略并应用DTO投影

如何解决JPQL HQL查询在类层次结构之上运行,具有连接的继承策略并应用DTO投影

鉴于我有以下具有继承策略的类层次结构:

1234heh

如何编写JPQL / HQL查询,该查询将返回@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() { } } ,其中List<NotificationDetails>是:

NotificationDetails

其中的映射应如下所示:

public class NotificationDetails {

    private final String contact;
    private final String content;

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

解决方法

Hibernate支持所谓的隐式子类型属性解析,因此您可以使用如下查询:

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();
,

您可以尝试使用以下jpql:

List<NotificationDetails> results = em.createQuery(
   "select new com.your.entities.NotificationDetails( "
 + "  coalesce(s.phoneNumber,p.application),"
 + "  coalesce(s.smsText,p.pushText) "
 + ") from Notification n "
 + "left join Sms s on s.id = n.id "
 + "left join Push p on p.id = n.id ",NotificationDetails.class).getResultList();

它可以工作,但是会生成效率很低的sql:

select
  coalesce(sms1_.sms_phone,push2_.push_app) as col_0_0_,coalesce(sms1_.sms_text,push2_.push_text) as col_1_0_ 
from TEST_SCHEMA.TST_NOTIFICATION notificati0_ 
left outer join (
   TEST_SCHEMA.TST_SMS sms1_ 
   inner join TEST_SCHEMA.TST_NOTIFICATION sms1_1_
      on sms1_.sms_not_id=sms1_1_.not_id
) on (sms1_.sms_not_id=notificati0_.not_id) 
left outer join (
   TEST_SCHEMA.TST_PUSH push2_ 
   inner join TEST_SCHEMA.TST_NOTIFICATION push2_1_ 
      on push2_.push_not_id=push2_1_.not_id
) on (push2_.push_not_id=notificati0_.not_id)

如果这里的性能很重要,我想最好使用本机查询并将其(通过@SqlResultSetMapping通过example映射到NotificationDetails dto。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。