我有一个与Path有0到多个关系的Project。我们对Path进行软删除,所以我试图生成一个返回带有活动路径的Project的查询,如果Project没有Path的实例,我仍然希望返回没有Path记录的Project。此外,如果Project只删除了Path记录,我仍然希望返回没有Path记录的Project。
在SQL中它看起来像这样:
select *
from project p
LEFT JOIN path pa ON p.project_id = pa.project_id AND pa.deleted_flag = false
where p.project_id = 1;
但是我尝试了JPA和HQL的WITH,但成效有限。 使用criteriabuilder和JPQL但不返回仅包含已删除路径的Project
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
String q = "SELECT p FROM Project AS p " +
"LEFT JOIN FETCH p.paths as pa " +
"WHERE (pa.pathId is null OR pa.deletedFlag <> true) AND p.projectId = :projectId";
TypedQuery<Project> projectTypedQuery = entityManager.createQuery(q, Project.class);
也通过JPQL尝试但它不起作用,因为它返回已删除的路径
String q = "SELECT p FROM Project AS p " +
"LEFT JOIN Path pa ON pa.projectByProjectId.projectId = p.projectId AND pa.deletedFlag <> true " +
"WHERE p.projectId = :projectId";
projectTypedQuery = entityManager.createQuery(q, Project.class);
Query query = entityManager.createQuery(q);
project = (Project) query.setParameter("projectId", projectId).getSingleResult();
下面的HQL也会返回已删除的路径:
Session session = entityManager.unwrap(Session.class);
q = "SELECT p FROM Project AS p " +
"LEFT JOIN p.paths pa with pa.deletedFlag = false " +
"WHERE p.projectId = :projectId";
Query query = entityManager.createQuery(q);
project = (Project) query.setParameter("projectId", projectId).getSingleResult();
有什么想法吗?