querydsl 3.3.0 – 在带有N个布尔参数的查询中使用带有elementcollections的collection.any()生成N个“存在”子查询

我试图在ElementCollection中查询匹配2个条件的特定项目.当我在QueryDSL中编写查询时,Hibernate生成的查询包含2个带子查询的存在语句,每个子查询包含我指定的1个标准.

这是一个例子:

@Entity
public class Person {
   @Id
   private Integer id;
}

@Entity
public class Project {

   @Id
   private Integer id;
   private boolean canned;

   @ElementCollection(fetch=FetchType.EAGER, targetClass=ProjectMember.class)
   @CollectionTable(name="Project_Person", joinColumns={@JoinColumn(name="projectId", nullable=false)})
   private Set<ProjectMember> members;
}

@Embeddable
public class ProjectMember {

   private Integer personId;
   private Integer projectId;
   private boolean overworked;
   private boolean underpaid;
}

现在,如果我尝试执行以下操作,我将获得多个存在的子查询,每个子查询都有一个我指定的标准:

  QProject project = QProject.project;
  QProjectMember members = project.members.any();
  new HibernateQuery(sessionFactory.getCurrentSession())
  .from(project).where(project.canned.eq(true).or(
  members.overworked.eq(true).and(members.underpaid.eq(true)))).list(project);

这是输出查询:

select project
from Project project
where project.canned = ?1 or exists (select 1
from Project projectd92b4
  inner join projectd92b4.members as project_membersaeb8a
where projectd92b4 = project and project_membersaeb8a.overworked = ?1) and exists (select 1
from Project project4b8ff
  inner join project4b8ff.members as project_membersb6de1
where project4b8ff = project and project_membersb6de1.underpaid = ?1)

如您所见,有2个存在语句,子查询各自具有2个条件之一.此查询不会产生正确的结果,因为我不希望项目中至少有一个成员“过度工作”且至少有一个成员“欠薪”;我想要一个项目,其中至少有一个项目成员“过度劳累”和“薪水不足”.我是否误解了“any()”的正确用法,或者这是一个错误?

最佳答案 每个any()用法都转换为它自己的子查询.如果需要组合多个条件,则需要自己编写子查询.

any()不是连接替代,但子查询存在快捷方式.也许这有帮助.

点赞