Last active
April 17, 2018 12:58
-
-
Save cherniag/c5d75b67d6e28df2050a6c395a91c036 to your computer and use it in GitHub Desktop.
Hibernate criteria query predicate avg value of children one to many collection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Override | |
public Predicate toPredicate(Root<ParentEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) { | |
List<Predicate> predicates = new ArrayList<>(); | |
if (filters.isEmpty()) { | |
return cb.conjunction(); | |
} | |
Subquery<Long> countChildren = query.subquery(Long.class); | |
Root<ChildEntity> countChildrenRoot = countVotes.from(ChildEntity.class); | |
Join countChildrenJoin = countChildrenRoot.join("parentField"); | |
countChildren.select(cb.count(countChildrenRoot.get(ID))); | |
countChildren.where(cb.equal(root.get(ID), countChildrenJoin.get(ID))); | |
Subquery<Long> sumChildren = query.subquery(Long.class); | |
Root<ChildEntity> sumChildrenRoot = sumChildren.from(ChildEntity.class); | |
Join sumChildrenJoin = sumChildrenRoot.join("parentField"); | |
sumChildren.select(cb.sum(sumChildrenRoot.get("intField"))); | |
sumChildren.where(cb.equal(root.get(ID), sumChildrenJoin.get(ID))); | |
Map<String, Expression> col = ImmutableMap.<String, Expression>builder() | |
.put("avgChildren", cb.quot(sumChildren, countChildren)) | |
.build(); | |
if (filters.get("avgChildren") != null) { | |
List<Double> range = (List<Double>) filters.remove("avgChildren"); | |
Assert.isTrue(range.size() == 2, "Range " + range + " should have 2 elements"); | |
predicates.add(cb.and(cb.between(col.get("avgChildren"), range.get(0), range.get(1)))); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Formula("(select sum(v1.int_field) from child_entity_table v1 where v1.parent_id = id)" + | |
"/" + | |
"(select count(v2.id) from child_entity_table v2 where v2.parent_id = id)") | |
private Float calculatedField; | |
@Formula("(select avg(c1.int_field * 1.0) from child_entity_table c1 where c1.parent_id = id)") | |
private Double calculatedField; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment