spring-data-jpa - 覆盖使用 EntityGraph 注释的 Spring-Data-JPA 默认方法会导致 QueryException

标签 spring-data-jpa querydsl

我正在尝试使用 Data-JPA 实现 EntityGraph,因为使用了 QueryDslPredicateExecutor<T>公开方法 findAll(Predicate, Pageable)我需要的那个,我试图覆盖它以使用 @EntityGraph 进行注释然后麻烦就开始了:

org.springframework.dao.InvalidDataAccessApiUsageException: 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=appointment,role=com.physioclinic.entity.Appointment.createdBy,tableName=user,tableAlias=user5_,origin=appointment appointmen0_,columns={appointmen0_.createdBy_id ,className=com.physioclinic.entity.User}}] [select count(appointment)
from com.physioclinic.entity.Appointment appointment where lower(concat(concat(appointment.patient.person.name,?1),appointment.patient.person.surname)) like ?2 escape '!']; nested exception is java.lang.IllegalArgumentException: 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=appointment,role=com.physioclinic.entity.Appointment.createdBy,tableName=user,tableAlias=user5_,origin=appointment appointmen0_,columns={appointmen0_.createdBy_id ,className=com.physioclinic.entity.User}}]

当我使用默认方法时,即使使用相同的 Predicate,也不会发生任何不好的事情。 ,但我不能使用 EntityGraph,我的实现或谓词有问题吗?

跟随场景中的对象:

实体
@Table(name = "appointment")
@Entity
@Getter
@Setter
@NamedEntityGraphs({@NamedEntityGraph(name = "graph.Appointment.default", includeAllAttributes = true,
    attributeNodes = {@NamedAttributeNode(value = "physiotherapist"),
        @NamedAttributeNode(value = "patient"),
        @NamedAttributeNode(value = "care")})})
public class Appointment extends PersistableAuditable<User, Long> {

    private static final long serialVersionUID = -4325126792470516159L;

    @DateTimeFormat(pattern = "dd/MM/yyyy")
    @NotNull
    @Column(name = "date")
    private LocalDate date;

    @DateTimeFormat(pattern = "HH:mm")
    @NotNull
    @Column(name = "schedule")
    private LocalTime schedule;

    @ManyToOne
    @JoinColumn(name = "physiotherapist", referencedColumnName = "id")
    private Physiotherapist physiotherapist;

    @ManyToOne
    @JoinColumn(name = "service", referencedColumnName = "id")
    private Service service;

    @ManyToOne
    @JoinColumn(name = "patient", referencedColumnName = "id")
    private Patient patient;

    @ManyToOne(cascade = CascadeType.REMOVE)
    @JoinColumn(name = "care", referencedColumnName = "id")
    private Care care;

    public Appointment(long id) {
        setId(id);
    }

    public Appointment() {
    }

    /**
     * Helpers
     */

    public boolean isSpecialPrice() {
        return care.getPrivateCare() && care.getSpecial() && care.getSpecialPrice() != null;
    }

    public boolean isPrivatePrice() {
        return care.getPrivateCare() && care.getHealthCare() == null;
    }

    public boolean isHealthCarePrice() {
        return !care.getPrivateCare() && care.getHealthCare() != null;
    }
}

存储库
public interface AppointmentRepository extends JpaRepository<Appointment, Long>,
                                               QueryDslPredicateExecutor<Appointment> {

    @EntityGraph(value = "graph.Appointment.default")
    Page<Appointment> findAll(Predicate predicate, Pageable pageable);
}

谓词
public final class AppointmentPredicate {

    private AppointmentPredicate() {
    }

    public static Predicate bySearch(String search) {
        QPerson person = QAppointment.appointment.patient.person;
        return person.name.concat(" ").concat(person.surname).containsIgnoreCase(search);
    }

}

最佳答案

我遇到了完全相同的问题,并且在调试 spring 源代码时获得了很多乐趣。 所以根本原因是:spring 正在对导致该错误的计数查询应用提示。

QueryDslJpaRepository.java:

@Override
public Page<T> findAll(Predicate predicate, Pageable pageable) {

    JPQLQuery countQuery = createQuery(predicate);
    JPQLQuery query = querydsl.applyPagination(pageable, createQuery(predicate));
....
}

protected JPQLQuery createQuery(Predicate... predicate) {

    JPAQuery query = querydsl.createQuery(path).where(predicate);
    CrudMethodMetadata metadata = getRepositoryMethodMetadata();

    if (metadata == null) {
        return query;
    }

    LockModeType type = metadata.getLockModeType();
    query = type == null ? query : query.setLockMode(type);

    for (Entry<String, Object> hint : getQueryHints().entrySet()) {
        query.setHint(hint.getKey(), hint.getValue());
    }

    return query;
}

解决方法是:为您的存储库接口(interface)创建一个支持接口(interface),并覆盖查询创建逻辑来实现它。这是我的午夜执行 (这只是一个原型(prototype),当然必须改进) .
public interface SomeRepository extends JpaRepository<SomeEntity, Long>, QueryDslPredicateExecutor<SomeEntity>, SomeRepositoryCustom {
}


public interface SomeRepositoryCustom {
    Page<SomeEntity> findAll(Predicate predicate, Pageable pageable);
}

public class SomeRepositoryImpl extends SimpleJpaRepository<SomeEntity, Long>
    implements SomeEntityRepositoryCustom
{
    private final EntityManager entityManager;
    private final EntityPath<SomeEntity> path;
    private final PathBuilder<SomeEntity> builder;
    private final Querydsl querydsl;

    @Autowired
    public SomeRepositoryImpl(EntityManager entityManager) {
        super(SomeEntity.class, entityManager);


        CrudMethodMetadata metadata = getRepositoryMethodMetadata();
        this.entityManager = entityManager;
        this.path = SimpleEntityPathResolver.INSTANCE.createPath(SomeEntity.class);
        this.builder = new PathBuilder<>(path.getType(), path.getMetadata());
        this.querydsl = new Querydsl(entityManager, builder);
    }

    @Override
    public Page<SomeEntity> findAll(Predicate predicate, Pageable pageable) {
        JPAQuery countQuery = createQuery(predicate);
        JPAQuery query = (JPAQuery) querydsl.applyPagination(pageable, createQuery(predicate));

        query.setHint(EntityGraph.EntityGraphType.LOAD.getKey(),
            entityManager.getEntityGraph("YOUR GRAPH KEY"));

        Long total = countQuery.count();
        List<SomeEntity> content = total > pageable.getOffset() ? query.list(path) :
            Collections.<SomeEntity> emptyList();

        return new PageImpl<>(content, pageable, total);
    }

    private JPAQuery createQuery(Predicate predicate) {
        return querydsl.createQuery(path).where(predicate);
    }

}

看起来这是一个错误,我将把它提交给 spring jpa jira。

关于spring-data-jpa - 覆盖使用 EntityGraph 注释的 Spring-Data-JPA 默认方法会导致 QueryException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27494988/

相关文章:

java - Spring Boot + Spring Batch + Spring JPA

java - EclipseLink 错误 : Entity class has no primary key specified. 它应该定义 @Id、@EmbeddedId 或 @IdClass

mysql - 带 CaseBuilder 的 EnumPath(QueryDSL 3.6.2)

java - 用于在 Java 学生关系表上支持不同过滤器集的设计模式

exists - QueryDSL 4 select + where + 存在

java - 使用 QueryDsl/Hibernate 进行延迟加载不起作用

java - Spring Data REST、QueryDSL 和 HashMaps - 引用 HashMap 属性时来自 URL 的 Null 谓词

java - Spring Boot 加载 orm.xml

java - Spring JpaRepositroy.save() 似乎不会在重复保存时抛出异常

java - spring-jpa 如何在 find* 查询方法上获取 EntityNotFoundException 或类似的异常?