spring data jpa规范join fetch不能正常工作

时间:2018-03-27 08:00:10

标签: spring join spring-data-jpa fetch jpa-criteria

我正在尝试使用Spring Data JPA Specificaiton来查询数据,但我在这里遇到了一些问题。 Java代码如下:

    List<NoticeEntity> studentNoticeEntityList = noticeRepository
            .findAll((root, criteriaQuery, criteriaBuilder) -> {
                criteriaQuery.distinct(true);

                root.fetch(NoticeEntity_.contentEntitySet, JoinType.LEFT);

                Predicate restrictions = criteriaBuilder.conjunction();

                SetJoin<NoticeEntity, UserNoticeEntity> recipientNoticeJoin = root
                        .join(NoticeEntity_.recipientNoticeEntitySet, JoinType.INNER);
                recipientNoticeJoin.on(criteriaBuilder.equal(
                        recipientNoticeJoin.get(UserNoticeEntity_.recipientStatus), NoticeRecipientStatus.Unread));
                Join<UserNoticeEntity, WeChatUserEntity> recipientUserJoin = recipientNoticeJoin
                        .join(UserNoticeEntity_.user);

                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.equal(recipientUserJoin.get(WeChatUserEntity_.id), id));
                // recipientNoticeJoin.fetch(UserNoticeEntity_.user, JoinType.INNER);

                return restrictions;
            });

当我评论代码“recipientNoticeJoin.fetch(UserNoticeEntity_.user,JoinType.INNER);”时,它工作正常,但是当我取消评论时,我会收到错误:

org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list 

所以,我想知道是否使用Specification方式支持join fetch,或者我的代码有问题。 我知道使用@Query(“some hql”)有另一种方法,但不知怎的,我只是喜欢使用规范方式。 非常感谢。

1 个答案:

答案 0 :(得分:2)

该错误表明您从选择列表中缺少实体。试试这个:

from .base import *

DEBUG = False

ALLOWED_HOSTS = ["*"]

MEDIA_ROOT = os.path.join(BASE_DIR, "images")
MEDIA_URL = '/snapcapsule/'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")

此外,休眠模式可能会首先运行一个计数查询来确定结果数,这可能导致上述错误。您可以通过在添加访存之前检查查询的返回类型来避免这种中断。

Eager fetching in a Spring Specification

相关问题