春季规范中的热切获取 [英] Eager fetching in a Spring Specification

查看:72
本文介绍了春季规范中的热切获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个Media对象:

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.

这里是规格:

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;
        }
    };
}

当指定channelType时,搜索"规范正确运行,因此联接有效.如何指定应该热切获取联接?

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?

我尝试添加

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

然后Hibernate引发异常:

Then Hibernate throws an exception:

org.hibernate.QueryException:查询指定了连接提取,但是选择列表[FromElement {explicit,不是集合连接,获取连接,获取非惰性属性,classAlias = generateAlias4 ...

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?

谢谢.

推荐答案

我认为您在计数查询方面遇到了问题.通常,该规范用于数据查询和计数查询.对于计数查询,没有媒体".我使用这种解决方法:

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.

这篇关于春季规范中的热切获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆