我有以下 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
}
我还有根实体的 spring-data-jpa 存储库:
public interface ObjectEntityRepository extends JpaRepository<ObjectEntity, UUID>, JpaSpecificationExecutor<ObjectEntity>{
}
我正在尝试使用 Page<T> findAll(Specification<T> spec, Pageable pageable)
方法JpaSpecificationExecutor
引入一页的 ObjectEntity
同时急切地加载所有集合(instances 和instances.clients)。这就是我陷入困境的地方:
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) ?
}
};
构造谓词以便引入所有惰性集合的正确方法是什么?
最佳答案
fetch() 方法返回 Fetch可以用作新 fetch() 的“根”的对象。
获取的内容存储在 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
}
};
关于java - 如何使用急切获取定义 "select *"JPA 谓词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28987063/