Specify to fetch lazy entity with Specification

Hi!
I use Spring’s Specification (that I believe is the analogue or wrapper over Criteria) and want to specify that entity must be loaded eagerly.
How to do it?
Trying this way:

             return spec.and((root, query, criteriaBuilder) -> {
                root.fetch("city", JoinType.LEFT);
                return criteriaBuilder.conjunction();
            });

but getting error:

org.hibernate.query.SemanticException: query specified join fetching, but the owner of the fetched association was not present in the select list [SqmSingularJoin(com.dating.model.User(123736953846700).city(123736954064400) : city)]

Well, that’s what you get when you use these “great” Spring abstractions :wink:

I guess that whatever Spring does involves selecting parts of the query root, but not the root itself. Possibly you’re using a projection? I’d recommend you to use an entity graph instead though.

The error you’re encountering suggests that you’re trying to join fetch a relationship in your Hibernate Criteria query, but the entity owner of the fetched association is not present in the select list. To resolve this issue, you need to include the owner entity in the select list.

You can modify your code as follows:

javaCopy code

return spec.and((root, query, criteriaBuilder) -> {
    root.fetch("city", JoinType.LEFT);
    query.distinct(true); // Add this line to include the owner entity in the select list
    return criteriaBuilder.conjunction();
[}]<a href="https://sutogames.com/blog/android-game-development-companies">))</a>

By adding query.distinct(true);, you ensure that the owner entity (in this case, the User entity) is included in the select list, allowing the fetch operation to work correctly. This should resolve the error you’re encountering.

The error you’re encountering suggests that you’re trying to join fetch a relationship in your Hibernate Criteria query, but the entity owner of the fetched association is not present in the select list. To resolve this issue, you need to include the owner entity in the select list.

You can modify your code as follows:
return spec.and((root, query, criteriaBuilder) → {
root.fetch(“city”, JoinType.LEFT);
query.distinct(true); // Add this line to include the owner entity in the select list
return criteriaBuilder.conjunction();
});
By adding query.distinct(true); , you ensure that the owner entity (in this case, the User entity) is included in the select list, allowing the fetch operation to work correctly. This should resolve the error you’re
encountering.

thanks, it works!
saw this in hibernate examples, but thought somewhy that it’s not needed in my case )

1 Like

well… sorry my fault, it’s appeared it’s not fixing the issue.
Previous time when I reported it was false-positive by tests… probably missed case.