问题描述
我正在努力编写一个JPA查询,该查询将返回数据库中的所有P个对象,并且在它们旁边,我希望对其属性A=1的S个子对象进行计数。
SQL查询
选择p.*,(从s_table s中选择计数(s.id) 其中p.id=s.p_id和s.PropertyA=1)来自p_table p映射:
@Entity
@Table(name = "t_table")
public class PTable{
@Id
private String id;
@Version
private Long version;
private String subject;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
@JoinColumn(name = "p_id", referencedColumnName = "id")
private Set<STable> sSet = new HashSet<>();
}
@Entity
@Table(name = "s_table")
public class STable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "p_id")
private String pId;
private String propertyA;
}
另外,您是否愿意指出任何用JPA编写复杂查询的好教程。
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<PTable> q = cb.createQuery(PTable.class);
Root<PTable> c = q.from(PTable.class);
推荐答案
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<MyPojo> cq = cb.createQuery(MyPojo.class);
Root<PTable> rootPTable = cq.from(PTable.class);
Join<PTable, STable> joinSTable = rootPTable.join(PTable_.sSet);
Subquery<Long> sqCount = cq.subquery(Long.class);
Root<STable> sqRootSTable = sqCount.from(STable.class);
Join<STable, PTable> sqJoinPTable = sqRootSTable.join(STable_.pSet);
sqCount.where(cb.and(
cb.equal(sqJoinPTable.get(PTable_.id),rootPTable.get(PTable_.id)),
cb.equal(sqRootSTable.get(STable_.propertyA),"1")));
sqCount.select(cb.count(sqRootSTable));
cq.multiselect(
rootPTable.get(PTable_.id),
rootPTable.get(PTable_.version),
rootPTable.get(PTable_.subject),
joinSTable.get(STable_.id),
sqCount.getSelection(),
);
您将需要一个POJO来获取构造函数具有的结果,该结果按顺序和类型与多选参数匹配,如下所示:
public MyPojo(String pId, Long version, String subject, Long sId, Long count){
[...]
}
您还必须更改实体以正确映射关系,通过双向和惰性操作来提高性能,如下所示:
可按键
@OneToMany(mappedBy="p",fetch = FetchType.LAZY)
private Set<STable> sSet;
稳定
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="id")
private PTable p;