如何使用eager fetch定义“select *”JPA谓词?

时间:2015-03-11 12:50:25

标签: java jpa spring-data spring-data-jpa

我有以下3个实体(请注意延迟集合的层次结构):

@Entity
public class ObjectEntity {
   @OneToMany(fetch = FetchType.LAZY)
   Set<ObjectInstanceEntity> instances;
}

@Entity
public class ObjectInstanceEntity {
   @OneToMany(fetch = FetchType.LAZY)
   Set<ObjectInstanceClientEntity> clients;
}

@Entity
public class ObjectInstanceClientEntity {
   //nothing special
}

我还有root实体的spring-data-jpa存储库:

public interface ObjectEntityRepository extends JpaRepository<ObjectEntity, UUID>, JpaSpecificationExecutor<ObjectEntity>{
}

我尝试使用Page<T> findAll(Specification<T> spec, Pageable pageable)上的JpaSpecificationExecutor方法引入页面值ObjectEntity,同时急切地加载所有集合(实例和实例客户端)。这就是我陷入困境的地方:

private final Specification<ObjectEntity> spec = new Specification<ObjectEntity>() {
    @Override
    public Predicate toPredicate(Root<ObjectEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        root.fetch("instances", JoinType.LEFT);
        root.fetch("instances.clients", JoinType.LEFT); //this doesnt work
        return cb.; //what do i put here? any(null) ?
    }
};

是什么构造谓词的正确方法,以便引入所有惰性连接?

1 个答案:

答案 0 :(得分:0)

fetch()方法返回一个Fetch对象,该对象可以用作新fetch()的“root”。

获取存储在Root对象中,您不必返回它。

在你的情况下:

private final Specification<ObjectEntity> spec = new Specification<ObjectEntity>() {
    @Override
    public Predicate toPredicate(Root<ObjectEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        root.fetch("instances", JoinType.LEFT).fetch("clients", JoinType.LEFT); //this should work
    }
};