我正在尝试创建一个条件,从3个表(关联,更新和细节)中检索一些对象.详细信息参考关联和更新,更新引用了详细信息列表.我的目标是在给定一个关联标识符的情况下,在指定的字段中检索至少具有空值的详细信息的更新列表.在JPQL中很容易做到,但客户端表示这必须用标准编码.
我的JPQL是:
- public List<Update> getUpdates(long associateId) {
- TypedQuery<Update> query = em.createQuery("select distinct u from Update u,Detail dt,Associate a "
- + "where dt.update = u and dt.associate = a and a.associateId = :id and "
- + "dt.ack_date is null",Update.class);
- query.setParameter("id",associateId);
- return query.getResultList();
- }
我尝试了以下,但它只是返回数据库中的所有更新:
- public List<Update> getUpdates(long associateId) {
- CriteriaBuilder builder = em.getCriteriaBuilder();
- CriteriaQuery<Update> query = builder.createQuery(Update.class);
- Root<Update> fromUpdates = query.from(Update.class);
- Root<Associate> fromAssociate = query.from(Associate.class);
- Root<Detail> fromDetail = query.from(Detail.class);
- Join<Detail,Associate> associateJoin = fromDetail.join("associate");
- Join<Detail,Update> updateJoin = fromDetail.join("update");
- TypedQuery<Update> typedQuery = em.createQuery(query
- .select(fromUpdates)
- .where(builder.and(
- builder.equal(fromAssociate.get("associateId"),associateId),builder.equal(fromDetail.get("associate"),associateJoin),builder.equal(fromDetail.get("update"),updateJoin),builder.isNull(fromDetail.get("ack_date"))
- ))
- .orderBy(builder.asc(fromUpdates.get("updateId")))
- .distinct(true)
- );
- return typedQuery.getResultList();
- }
有人可以帮我吗我搜索,但找不到任何与3个实体的例子.
解决方法
每个连接都可以将您从左边的类型参数传给最右边的参数.所以,我的代码(第二行)的细节连接从fromUpdates开始,这是一个Path< Update>,并创建了一些幕后的路径< Detail>.从此,您可以构建其他连接.尝试这个(代码未测试):
- Root<Update> fromUpdates = query.from(Update.class);
- Join<Update,Detail> details = fromUpdates.join("details");
- Join<Detail,Associate> associate = details.join("associate");
- List<Predicate> conditions = new ArrayList();
- conditions.add(builder.equal(associate.get("associateId"),associateId));
- conditions.add(builder.isNull(details.get("ack_date")));
- TypedQuery<Update> typedQuery = em.createQuery(query
- .select(fromUpdates)
- .where(conditions.toArray(new Predicate[] {}))
- .orderBy(builder.asc(fromUpdates.get("updateId")))
- .distinct(true)
- );