2

I’m struggling with reusing a Specification<T> inside another one.

Entities:

  • Group has a list of StudentGroupInfo.

  • I already have a Specification<Group> that can filter Group by various conditions (joins, group by, having, etc.).

  • Now I need to count all StudentGroupInfo for the groups that are matched by this Specification<Group>.

Repository:

public interface StudentGroupInfoRepository extends JpaRepository<StudentGroupInfo, Long> {
    long count(Specification<StudentGroupInfo> specification);
}

Attempt to reuse the group specification via subquery:

private Specification<StudentGroupInfo> buildSpecificationByGroupSpecification(
        Specification<Group> groupSpecification) {
    return (root, query, builder) -> {
        var subquery = query.subquery(Long.class);
        var groupRoot = subquery.from(Group.class);

        // how to apply the groupSpecification here?
        var groupPredicate = groupSpecification.toPredicate(groupRoot, query /* ??? */, builder);

        subquery.select(groupRoot.get(BaseEntity.Fields.id))
                .where(groupPredicate);
        return root.get(StudentGroupInfo.Fields.group).in(subquery);
    };
}

Problem:

If the groupSpecification is simple, it works. But if it contains joins, group by or having, Hibernate throws:

Caused by: org.hibernate.sql.ast.SqlTreeCreationException: Could not locate TableGroup - com.sdx.rootservice.model.group.Group(...)

I assume it happens because I pass the outer query into groupSpecification.toPredicate(...), while that Specification expects a root from the main query, not from a subquery.

Question:

How can I properly reuse an existing Specification<Group> inside a subquery in another specification, or do I need a different approach for it (e.g. refactor to join instead of subquery)?

3
  • This question seems to have been generated or "improved" with help of ChatGPT or another AI. Please be aware that using LLMs or other AIs to generate content is not allowed. Commented Aug 26 at 12:56
  • Also, please ask only one question per question. Commented Aug 26 at 12:57
  • @MarkRotteveel, thank you, I didn't know that. I asked ChatGPT only about a structure of the question and to edit my English text because unfortunately I have some problems with that and I am a bit happier when my text is clear for you all :). And yes, I will edit it to one question somehow, because I thought those question are touching each other. Thank you for your comments Commented Aug 28 at 18:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.