【发布时间】:2021-02-15 04:49:01
【问题描述】:
假设我有 1 个父实体和 2 个子实体:
@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() {
}
}
我想使用 JPA 标准 API 进行投影,如下所示:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<NotificationSummary> query = builder.createQuery(NotificationSummary.class);
Root<Notification> root = query.from(Notification.class);
query.select(builder.construct(NotificationSummary.class,
root.get("code"),
builder.treat(root, Sms.class).get("smsText"),
builder.treat(root, Push.class).get("pushText"),
builder.treat(root, Sms.class).get("phoneNumber"),
builder.treat(root, Push.class).get("application")
));
class NotificationSummary {
private final Long code;
private final String smsText;
private final String pushText;
private final String phoneNumber;
private final String application;
public NotificationSummary(Long code, String smsText, String pushText, String phoneNumber, String application) {
this.code = code;
this.smsText = smsText;
this.pushText = pushText;
this.phoneNumber = phoneNumber;
this.application = application;
}
}
当我执行它时,它会生成 SQL 查询:
select
notificati0_.code as col_1_0_,
notificati0_3_.sms_text as col_5_0_,
notificati0_2_.push_text as col_6_0_,
notificati0_3_.phone_number as col_7_0_,
notificati0_2_.application as col_8_0_
from
notification notificati0_
inner join
push notificati0_2_
on notificati0_.id=notificati0_2_.notification_id
inner join
sms notificati0_3_
on notificati0_.id=notificati0_3_.notification_id
我希望它是左外连接。
我可以以某种方式将其更改为左外连接而不是内连接吗?
【问题讨论】:
标签: hibernate jpa spring-data-jpa jpa-2.0 criteria-api