将oracle转换为JPA createQuery

时间:2012-10-31 11:39:24

标签: oracle jpa

SELECT * 
FROM 
  CUSTOMER_MASTER t0, 
  (SELECT t1.COMMNUMBER, t1.COMMTYPE FROM FOLLOWUP_GUIDES t1 WHERE (t1.STAGE_ID = '5')) t2
WHERE (t0.FOLL_UP_NUM = t2.COMMNUMBER 
and T0.FOLL_UP_TYPE=t2.COMMTYPE AND (t0.COMPANY_ID = 'C001'))

在上面的oracle查询中,我必须在组合commnumber和commtype中获得follupnum和folluptype。但是可以在JPA中编写此查询吗?

3 个答案:

答案 0 :(得分:1)

JPA完全支持SQL查询。您可以使用createNativeQuery(sql)或@NamedNativeQuery。

您也可以根据JPQL重新编写查询。

如果您正在使用EclipseLink,它确实支持JPQL中FROM子句中的子选择,

http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL#Sub-selects_in_FROM_clause

答案 1 :(得分:1)

JPA完全支持SQL查询。您可以使用createNativeQuery(sql)或@NamedNativeQuery

点击此link

答案 2 :(得分:0)

假设您在CUSTOMER_MASTER和FOLLOWUP_GUIDES之间有外键

即。假设

CUSTOMER_MASTER.FOLL_UP_NUM    is FK to   FOLLOWUP_GUIDES.COMMNUMBER 
CUSTOMER_MASTER.FOLL_UP_TYPE   is FK to   FOLLOWUP_GUIDES.COMMTYPE

然后你的查询

SELECT * 
FROM 
  CUSTOMER_MASTER t0, 
  (SELECT t1.COMMNUMBER, t1.COMMTYPE FROM FOLLOWUP_GUIDES t1 
   WHERE (t1.STAGE_ID = '5')) t2
WHERE (t0.FOLL_UP_NUM = t2.COMMNUMBER 
and T0.FOLL_UP_TYPE=t2.COMMTYPE AND (t0.COMPANY_ID = 'C001'))

相当于

SELECT t0.*
FROM CUSTOMER_MASTER t0 JOIN FOLLOWUP_GUIDES t1
WHERE t0.COMPANY_ID = 'C001'
AND   t1.STAGE_ID = '5'

这可以很容易地在JPA中完成,看起来非常类似于这个SQL(只使用对象名和字段名而不是表名和属性名)。

JPA JPQL查询将如下所示:

SELECT t0
FROM CustomerMaster t0 JOIN FollowupGuides t1
WHERE t0.companyId = "C001"
AND   t1.stageId = "5"

也可以使用JPA子查询:

SELECT t0
FROM CustomerMaster t0 
WHERE t0.companyId = "C001"
AND   EXISTS (SELECT 1
              FROM FollowupGuides t1
              WHERE t1.commnumber = t0.follUpNum
              AND   t1.commtype = t0.FollUpType
              AND   t1.stageId = "5")

= B)