我正在尝试创建一个查询,该查询应返回子类型(InternalTask​​和ExternalTask​​的列表)。这很好用,但是我想在查询中为其中一个子类型添加一个where子句。我尝试了以下方法:

实体:

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "TASK_TYPE")
public abstract class Task {
    ...
}

@Entity
@DiscriminatorValue("INTERNAL")
public class InternalTask extends Task {
    ...
    private Employee employee;
    ...
}

@Entity
@DiscriminatorValue("EXTERNAL")
public class ExternalTask extends Task {
    ...
}

功能:
public List<? extends Task> findTasks(TaskSearch taskSearch) {
    JPAQuery query = new JPAQuery(entityManager);

    QTask task = QTask.task;
    BooleanBuilder where = new BooleanBuilder();

    if (taskSearch.getEmployee() != null) {
        where.and(task.instanceOf(InternalTask.class).and(task.as(QInternalTask.class).employee.eq(taskSearch.getEmployee())));
    }

    query.from(task).where(where).orderBy(task.deadline.asc());

    return query.list(task);
}

错误:
An error occurred while parsing the query filter "select task_
from Task task_
where (type(task_) = ?1 and task_.employee = ?2)
order by task_.deadline asc". Error message: No field named "employee" in "Task". Did you mean "deadline"? Expected one of the available field names in "com.exampe.Task": "[deadline]".

如您所见,它被转换为不知道子类型InternalTask​​的Task实体上的select。有没有办法完成子类型的where子句?

最佳答案

我通过添加subQuery找到了解决方案:

public List<? extends Task> findTasks(TaskSearch taskSearch) {
    JPAQuery query = new JPAQuery(entityManager);

    QTask task = QTask.task;
    QInternalTask internalTask = QInternalTask.internaltask;
    BooleanBuilder where = new BooleanBuilder();

    if (taskSearch.getEmployee() != null) {
        JPASubQuery from = new JPASubQuery().from(internalTask)
                .where(internalTask.employee.eq(taskSearch.getEmployee()).and(internalTask.id.eq(task.id)));
        where.and(from.exists());
    }

    query.from(task).where(where).orderBy(task.deadline.asc());

    return query.list(task);
}

07-24 13:43