[使用Criteria API开发Spring Boot应用程序时遇到问题。
我有一个简单的Employer
实体,其中包含一组Job.ID
(不是实体,需要时使用存储库将其拉出)。 Employer
和Job
具有多对多关系。此映射仅用于查找没有工作的雇员。
public class Employer {
@ElementCollection
@CollectionTable(
name = "EMPLOYEE_JOBS"
joinColumns = @JoinColumn(name = "EMP_ID")
@Column(name = "JOB_ID")
private final Set<String> jobs = new HashSet<>(); //list of ids of jobs for an employee
}
然后我有一个通用函数,该函数通过给定的attributePath和命令返回谓词(规范),以执行任何IEntity
实现。
public <E extends IEntity> Specification<E> createPredicate(String attributePath, String command) {
return (r, q, b) -> {
Path<?> currentPath = r;
for(String attr : attributePath.split("\\.")) {
currentPath = currentPath.get(attr);
}
if(Collection.class.isAssignableFrom(currentPath.getJavaType())) {
//currentPath points to PluralAttribute
if(command.equalsIgnoreCase("empty")) {
return b.isEmpty((Expression<Collection<?>>)currentPath);
}
}
}
}
如果要获取当前没有工作的所有雇员的清单,希望我可以按如下方式创建谓词:
Specification<Employer> spec = createPredicate("jobs", "empty");
//or if I want only `Work`s whose were done by employer with no job at this moment
Specification<Work> spec = createPredicate("employerFinished.jobs", "empty");
不幸的是,这不起作用,并引发以下异常:
org.hibernate.hql.internal.ast.QuerySyntaxException:
unexpected end of subtree
[select generatedAlias0 from Employer as generatedAlias0
where generatedAlias0.jobs is empty]
是否有解决方法,使这项工作有效?
Hibernate中的此错误自2011年9月以来就为人所知,但可惜的是尚未修复。https://hibernate.atlassian.net/browse/HHH-6686可能是因为有一个非常简单的解决方法,而不是:
"where generatedAlias0.jobs is empty"
您可以使用
"where size(generatedAlias0.jobs) = 0"
这样查询将按预期方式工作。