Java 针对OneToMany关系的Spring数据JPA选择

Java 针对OneToMany关系的Spring数据JPA选择,java,spring-boot,spring-data-jpa,querydsl,criteria-api,Java,Spring Boot,Spring Data Jpa,Querydsl,Criteria Api,我有两个实体 一个盒子有很多东西 现在,我想找出一个盒子,里面有很多详细信息,比如氧化剂,srNo,箱号,底价,洛蒂德,批号,尺寸 在编程方式下,仅使用单个选择查询(带条件API)的Criteria或queryDSL: CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<YourPojo> cq = cb.createQuery(YourPojo.class); Root<Box>

我有两个实体

一个盒子有很多东西 现在,我想找出一个盒子,里面有很多详细信息,比如氧化剂,srNo,箱号,底价,洛蒂德,批号,尺寸 在编程方式下,仅使用单个选择查询(带条件API)的Criteria或queryDSL:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<YourPojo> cq = cb.createQuery(YourPojo.class);

Root<Box> rootBox = cq.from(Box.class);
Join<Box,Lot> joinLot = rootBox.join(Box_.lots,JoinType.LEFT);

List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.equal(joinLot.get(Lot_.id), ID_LOT))
cq.where(predicates.toArray(new Predicate[predicates.size()]));

cq.multiselect(
    rootBox.get(Box_.id),
    rootBox.get(Box_.srNo),
    rootBox.get(Box_.boxNumber),
    rootBox.get(Box_.basePrice),
    rootBox.get(Box_.baseAmount),
    joinLot.get(Let_.id),
    joinLot.get(Let_.lotNumber),
    joinLot.get(Let_.size),
    joinLot.get(Let_.description),
    joinLot.get(Let_.pcs),
    joinLot.get(Let_.weight)
);

List<YourPojo> result = entityManager.createQuery(cq).getResultList();
通过这种方式,您将为每个箱子批次条目获得一个对象

另一种对我来说不太理想的方法是: CriteriaBuilder cb=entityManager.getCriteriaBuilder; CriteriaQuery cq=cb.createQueryBox.class

Root<Box> rootBox = cq.from(Box.class);
Join<Box,Lot> joinLot = (Join<Box,Lot>)rootBox.fetch(Box_.lots,JoinType.LEFT);

List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.equal(joinLot.get(Lot_.id), ID_LOT))
cq.where(predicates.toArray(new Predicate[predicates.size()]));

cq.select(rootBox);

List<Box> result = entityManager.createQuery(cq).getResultList();
通过这种方式,您将获得一个包含参数Lots list或Lot set fed的长方体实体列表

我更喜欢第一种模式,因为即使您有N个输入来处理Java8的流和lambda,它也非常简单,如果是API,则暴露实体是一种安全缺陷,这样您就可以处理平面对象

public YourPojo(Long id, String srNo, Integer boxNumber, Long basePrice, Long 
    baseAmount, Long idLot, Integer lotNumber, Long size, String description, 
    Integer pcs, Long weight){
     ....
}
Root<Box> rootBox = cq.from(Box.class);
Join<Box,Lot> joinLot = (Join<Box,Lot>)rootBox.fetch(Box_.lots,JoinType.LEFT);

List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.equal(joinLot.get(Lot_.id), ID_LOT))
cq.where(predicates.toArray(new Predicate[predicates.size()]));

cq.select(rootBox);

List<Box> result = entityManager.createQuery(cq).getResultList();