我正在尝试使用实体图来触发延迟集合加载,但不幸的是实体图也会触发所有嵌套集合。我正在使用 spring-data-jpa-entity-graph 库在运行时创建实体图。
@Entity
public class Brand implements Serializable {
@OneToMany(mappedBy = "brand", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<Vehicle> vehicles;
}
@Entity
public class Vehicle implements Serializable {
@ManyToOne
@JoinColumn(name = "brand_id")
private Brand brand;
@OneToMany(mappedBy = "vehicle", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<VehiclePart> parts;
}
@Entity
public class VehiclePart implements Serializable {
@ManyToOne
@JoinColumn(name = "vehicle_id")
private Vehicle vehicle;
}
带有 JPA 存储库的 Spring 服务:
public interface BrandsRepository extends EntityGraphJpaRepository<Brand, Long> {
Page<Brand> findAll(Pagable pagable, EntityGraph entityGraph);
}
@Service
public class BrandsService {
public List<Brand> find() {
return repository.findAll(PageRequest.of(0, 10, Sort.by(Sort.Direction.ASC, "id")), EntityGraphUtils.fromAttributePaths("vehicles")).getContent();
}
}
在这种情况下,服务还返回每辆车的零件收集,但我只想获取每个品牌的车辆收集的品牌列表。
我们如何触发仅在第一级加载惰性集合(仅品牌车辆 - 没有车辆零件)?