Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eager fetching in a Spring Specification

We have a Media object:

public class Media implements Serializable {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(insertable = false, updatable = false)
    private Long id;
    // other attributes
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "channelId", referencedColumnName = "id")
    private Channel channel;
    // getters, setters, hashCode, equals, etc.

}

The eager fetch of the channel parent works in regular repository methods, but not when using a Specification.

Here's the Specification:

public class MediaSpecs {

public static Specification<Media> search(final Long partnerId, final Integer width, final Integer height,
        final String channelType) {

    return new Specification<Media>() {

        @Override
        public Predicate toPredicate(Root<Media> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            Predicate restrictions = cb.equal(root.get("archived"), false);
            // other restrictions are and-ed together
            if (channelType != null) {
                    Join<Media, ChannelType> join = root.join("channel").join("orgChannelType").join("type");
                restrictions = cb.and(cb.equal(join.get("type"), channelType));
            }
            return restrictions;
        }
    };
}

The "search" spec works correctly when channelType is specified, so the join is working. How do I specify that the joins should be eagerly fetched?

I tried adding

Fetch<Media, ChannelType> fetch = root.fetch("channel").fetch("orgChannelType").fetch("type");

Then Hibernate throws an exception:

org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=generatedAlias4 ...

How do I add the associations to the select list?

Thanks.

like image 258
Eric Avatar asked Jan 12 '15 19:01

Eric


2 Answers

I think you have problem with count query. Usually the specification is use for data query a and count query. And for count query there is no "Media". I use this workaround :

Class<?> clazz = query.getResultType();
if (clazz.equals(Media.class)) {
    root.fetch("channel");
}

This use fetch only for data query a not for count query.

like image 129
Tomas Jacko Avatar answered Oct 10 '22 19:10

Tomas Jacko


For example:

public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                if (Long.class != query.getResultType()) {
                    root.fetch(Person_.addresses);
                }
                return cb.conjunction();
            }
like image 42
Eugene Avatar answered Oct 10 '22 19:10

Eugene