问题
I am attempting to query for a specific item in an ElementCollection that matches 2 criteria. When I write the query in QueryDSL, the query generated by Hibernate includes 2 exists statements with subqueries, each subquery contains 1 of the criterion I specified. Here is an example:
@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;
}
Now if I try to do the following, I will get multiple exists subqueries, each having one criterion I specify:
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);
Here is the output query:
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)
As you can see, there are 2 exists statements with subqueries each having one of the 2 criteria. This query will not produce the correct results as I don't want a project where at least 1 of the members is "overworked" and at least 1 member is "underpaid"; I want a project where at least 1 project member is both "overworked" AND "underpaid." Am I misunderstanding the proper use of "any()" or is this a bug?
回答1:
Each any() usage is converted into it's own subquery. If you need to combine multiple conditions you will need to write the subquery yourself.
any() isn't a join alternative, but a subquery exists shortcut. Maybe that helps.
来源:https://stackoverflow.com/questions/25435275/querydsl-3-3-0-using-collection-any-with-elementcollections-in-a-query-with