渴望在Spring规范中获取

时间:2015-01-12 19:13:29

标签: java spring jpa spring-data-jpa

我们有一个Media对象:

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.

}

通道父级的急切提取在常规存储库方法中有效,但在使用规范时则无效。

这是规范:

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

&#34;搜索&#34;指定channelType时,spec正常工作,因此连接正常。如何指定应该急切地获取连接?

我尝试添加

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

然后Hibernate抛出异常:

org.hibernate.QueryException:查询指定的连接提取,但是提取的关联的所有者在选择列表中不存在[FromElement {显式,不是集合连接,获取连接,获取非延迟属性,classAlias = generatedAlias4 ...

如何将关联添加到选择列表?

感谢。

3 个答案:

答案 0 :(得分:12)

我认为你有计数查询的问题。通常该规范用于数据查询和计数查询。对于计数查询,没有&#34; Media&#34;。我使用此解决方法:

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

这仅用于数据查询,而不用于计数查询。

答案 1 :(得分:0)

例如:

public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                if (Long.class != query.getResultType()) {
                    root.fetch(Person_.addresses);
                }
                return cb.conjunction();
            }

答案 2 :(得分:0)

有同样的问题。计数选择是问题。 if 语句对我来说一切正常

相关问题