我有一个看起来像这样的实体
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "status_type", length = 1, discriminatorType = DiscriminatorType.STRING)
@DiscriminatorOptions(force = true)
@Table(name = "EnrollmentStatus")
@AttributeOverride(name = AbstractGeneratedUUIDEntity.ID_NAME, column = @Column(name = EnrollmentStatus.ENROLLMENT_STATUS_ID_COLUMN, length = 36))
public abstract class EnrollmentStatus extends AbstractGeneratedUUIDEntity {
}
然后有EnrollmentStatus的子类,看起来像这样:
@Entity
@DiscriminatorValue("E")
public class EnrollmentStatusEnrolled extends EnrollmentStatus {
}
我需要编写选择status_type
的JPQL查询。我发现的唯一解决方案是:
SELECT new com.casenet.dao.enrollment.TimelineProgramEnrollmentQueryResult(prog.id, stat.date, TYPE(stat))
FROM ProgramEnrollment prog
INNER JOIN prog.statuses stat
WHERE prog.obsolete = 0
AND (stat.date >= :startDate and stat.date <= :endDate)
ORDER BY stat.date ASC
问题是TYPE(stat)没有选择值E
作为我期望的字符串,但选择了Class
和一堆元数据。我可以像这样在Java中访问DiscriminatorValue,但是一点也不好。
public TimelineProgramEnrollmentQueryResult(String enrollmentId, LocalDate statusDate, Object status) {
this.enrollmentId = enrollmentId;
this.statusDate = statusDate;
Annotation[] declaredAnnotations = ((Class) status).getDeclaredAnnotations();
for (Annotation annoation : declaredAnnotations) {
if (annoation instanceof DiscriminatorValue) {
this.statusType = ((DiscriminatorValue) annoation).value();
}
}
}
是否存在一种从JPQL查询中选择DiscriminatorValue
(不是作为TYPE而是作为值的字符串,应该是String的优美方法?
但是您可以将status_type列映射为只读属性:
@Column(name = "status_type", insertable=false, updateable=false)
private String statusType;
然后在查询中使用此属性。