我有一个名为Group的实体类,该实体类具有层次结构并使用ID引用指示父级。我的CriteriaQuery返回的结果太多了(几乎所有Groups),我无法弄清缺少的内容。
getChildrenNames()方法通常会触发log.warn()警告。
每个组可以有1个或多个由Group.parentIDs定义的父母。实际上,通常有0或1个父母。
public List<String> getChildrenNames(Group group) {
CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<String> criteriaQuery = builder.createQuery(String.class);
Root<Group> root = criteriaQuery.from(Group.class);
criteriaQuery.where( createParentPredicate(group, criteriaQuery) );
/*
* Return only the group names not the entire Group entity
*/
criteriaQuery.select(root.get(GroupModelAttributes.COL_NAME));
List<String> results = getEntityManager().createQuery(criteriaQuery).getResultList();
if (results != null && results.size() > 100)
log.warn("Detected unusually large number of children names for group \"%s\" COUNT: %d",
group.getName(), results.size());
return results != null && results.size() > 0 ? results : null;
}
private Predicate createParentPredicate(Group group, CriteriaQuery<?> criteriaQuery) {
String groupID = group.getID();
Validate.notNull(groupID, "Group has no ID: " + group);
String column = GroupModelAttributes.COL_PARENTIDS;
CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
Root<Group> root = criteriaQuery.from(Group.class);
Expression<Collection<String>> colLoc = root.get(column);
return builder.isMember(groupID, colLoc);
}
@Entity()
@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "name" }),
@UniqueConstraint(columnNames = { "iD" }) }, name = "T_Group")
public class Group {
@Basic()
@Column(name = "ID")
private String iD = null;
@Basic()
@Column(name = "Name")
private String name = null;
@ElementCollection(fetch = FetchType.EAGER)
@Column(name = "T_element")
@CollectionTable(joinColumns = { @JoinColumn(name = "Group_id") }, name = "Group_ParentIDs")
private Set<String> parentIDs = new HashSet<String>();
}
答案 0 :(得分:0)
我终于发现问题出在createParentPredicate()中,我创建了一个新的Root实例。这是有效的createParentPredicate():
{{1}}