问题描述
我有两个实体
Box(id,srNo,BoxNumber,basePrice,baseAmount)
Lot(id,lotNumber,size,description,pcs,weight,Box_id)
一个盒子有很多很多
现在,我想找出具有很多详细信息的框(BoxId,srNo,BoxNumber,basePrice,lotId,lotNumber,大小)
以编程方式(标准或queryDSL),仅使用一个选择查询
解决方法
使用Criteria API:
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();
以及YourPojo.java中的以下构造函数:
public YourPojo(Long id,String srNo,Integer boxNumber,Long basePrice,Long
baseAmount,Long idLot,Integer lotNumber,Long size,String description,Integer pcs,Long weight){
....
}
这样,您将为每个Box-Lot条目获得一个对象。
另一种方法,对我而言,最佳方法如下: CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(Box.class);
Root<Box> rootBox = cq.from(Box.class);
Join<Box,Lot> joinLot = (Join<Box,Lot>)rootBox.fetch(Box_.lots,ID_LOT))
cq.where(predicates.toArray(new Predicate[predicates.size()]));
cq.select(rootBox);
List<Box> result = entityManager.createQuery(cq).getResultList();
通过这种方式,您将获得一个Box实体的列表,并带有参数Lots(列表或地块集)。
我更喜欢第一种模式,因为即使您有N个输入来处理Java 8的流和lambda,它也非常简单,并且如果是API,则暴露实体是一个安全漏洞,这样您就可以将适用于平面对象。