简体   繁体   English

我可以将此Mysql查询转换为JPA吗?

[英]Can I convert this Mysql query to JPA?

I'm fairly familiar with SQL but very new to the Java Persistence API. 我对SQL相当熟悉,但是对Java Persistence API还是很新的。 I'm using JPA through the Play Framework. 我正在通过Play框架使用JPA。

I have the following MySql query that I'd like to convert to pure JPA code if I can: 我有以下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;

The purpose of this query is to select two rows from the Rankable table, but ensure that this specific pair is not present in the Comparison table. 该查询的目的是从“可排名”表中选择两行,但要确保“比较”表中不存在该特定对。

What would be the best way to call a somewhat complicated query like this from Play/JPA? 从Play / JPA调用这样的复杂查询的最佳方法是什么?

It is possible to do a self join in JPA. 可以在JPA中进行自我加入。

Take a look at this example 这个例子

from the 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"),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM