QueryDSL继承:where子句中的子类型

时间:2015-12-04 20:47:13

标签: java openjpa querydsl

我试图创建一个应该返回子类型的查询(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]".

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

1 个答案:

答案 0 :(得分:1)

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

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);
}