我想創建一個類型化的查詢。如何在有類型的查詢中制定JOIN?
TypedQuery<PubThread> query = em.createQuery(queryString, PubThread.class);
query.setParameter("threadId", threadId);
List<PubThread> otherPubThreads = query.getResultList();
查詢字符串中執行下面的SQL(目前沒有PARAM和靜態選擇值)
SELECT pt2 FROM pubthread pt2
JOIN pub_pubthread ppt2 ON pt2.id = ppt2.pubThreads_id
JOIN pub p2 ON ppt2.pups_id = p2.id
JOIN pubcategory pc2 ON p2.pubCategoryId = pc2.id
WHERE pt2.id != 1 and EXISTS (
SELECT DISTINCT(pt.id)
FROM pubthread pt
JOIN pub_pubthread ppt ON pt.id = ppt.pubThreads_id
JOIN pub p ON ppt.pups_id = p.id
JOIN pubcategory pc ON p.pubCategoryId = pc.id
WHERE pc2.id = pc.id and pt.id = 1
)
它的工作,如果我限制字符串一個簡單的選擇:SELECT Distinct(pt2.id), pt2.name FROM pubthread pt2
。一旦我添加JOIN線,它會抱怨。如何在JPA中正確查詢JOINS?錯誤是: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ON near line 1, column 81 [SELECT pt2 FROM com.brayan.webapp.model.PubThread pt2 JOIN pub_pubthread ppt2 ON pt2.id = ppt2.pubThreads_id ]
毫無疑問,標準查詢會更好。我接受這是解決方案空間的一部分。
爲什麼在子查詢中使用DISTINCT存在?沒有它,速度會更快。 –