2011-01-28 78 views
2

我對SQL非常熟悉,但對Java持久性API很新穎。我通過Play框架使用JPA。我可以將此Mysql查詢轉換爲JPA嗎?

我有以下MySQL查詢,我想,如果我可以轉換爲純JPA代碼:

SELECT a.id, b.id 
FROM Rankable a 
INNER JOIN Rankable b on a.id < b.id 
WHERE 
    a.category_id = ? AND b.category_id = ? 
    AND NOT EXISTS (
    SELECT * 
    FROM Comparison c 
    WHERE c.lower in (a.id, b.id)) 
    AND NOT EXISTS (
    SELECT * 
    FROM Comparison c 
    WHERE c.higher IN (a.id, b.id)) 
ORDER BY a.id * rand() 
LIMIT 1; 

此查詢的目的是從Rankable表中選擇兩行,但要確保該特定對不在比較表中。

什麼是從Play/JPA調用像這樣的複雜查詢的最佳方式?

+0

第一眼查詢看起來幾乎相同,因爲它會在JPA。我在那裏看到的唯一可疑問題是「rand()」和「LIMIT」。自然地「?」必須用參數的另一個語法(:param1等)替換。除此之外還有哪些問題? – 2011-01-28 19:16:30

回答

1

可以在JPA中進行自加入。

看看this example

從例如

@NamedQuery(name="siblings", query="select distinct sibling1 " 
    + "from Deity sibling1, Deity sibling2 where " 
    + "sibling1.father = sibling2.father " 
    + "and sibling1.mother = sibling2.mother " 
    + "and sibling2 = ?1 and sibling1 <> ?1"),