Tôi đang cố tạo một tiêu chí để truy xuất một số đối tượng từ 3 bảng (Liên kết, Cập nhật và Chi tiết). Chi tiết có tham chiếu đến Liên kết và Cập nhật và Bản cập nhật có tham chiếu đến danh sách Chi tiết. Mục tiêu của tôi là lấy một danh sách các bản Cập Nhật có ít nhất một chi tiết có giá trị null trong một trường được chỉ định, cho một ID liên kết. Trong JPQL dễ thực hiện nhưng khách hàng nói rằng điều này phải được mã hóa với các tiêu chí.Tiêu chí JPA 2 với 3 bảng
JPQL của tôi là:
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();
}
Tôi đã thử các sau đây, nhưng nó chỉ trả lại tất cả cập nhật trong cơ sở dữ liệu:
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();
}
bất cứ ai có thể giúp tôi? Tôi đã tìm kiếm nhưng không thể tìm thấy bất kỳ ví dụ nào với 3 thực thể.
Làm việc như một nét duyên dáng! Những tiêu chí này đã khiến tôi phát điên, nhưng điều này đã giúp ích rất nhiều! Cảm ơn bạn perissf :) –