2014-09-30 146 views
0

我怎麼能說出下面的MySQL查詢在JPQL轉換MySQL查詢JPQL查詢

select * from Price WHERE `valueDate` = (SELECT MAX(`valueDate`) FROM Price) and fundId = 2930 

我曾嘗試如下:這種辦法

"select a from Price a where a.valueDate = select MAX(a.valueDate) and a.fund.id = :" +Price.QUERY_PARAM_FUND_ID 

,但得到的錯誤:

Caused by: <openjpa-2.3.0-r422266:1540826 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: "Encountered "MAX" at character 50, but expected: ["AND", "GROUP", "HAVING", "OR", "ORDER", <EOF>]." while parsing JPQL "select a from Price a where a.valueDate = select MAX(b.valueDate) from Price b and a.fund.id = :fundId" 
+0

請顯示一些努力,顯示你已經嘗試過。人們會更熱衷於幫助,而你的問題更可能保持不變。 – Magnilex 2014-09-30 11:21:19

+0

你好,我已經添加了我的嘗試。感謝您的回覆 – 2014-09-30 11:24:45

+0

錯誤是什麼?你能把它粘貼在這裏嗎? – 2014-09-30 11:28:08

回答

0

我認爲它會工作,如果你會在子查詢之前和之後添加括號。

「從價格選擇其中a.valueDate =(SELECT MAX(a.valueDate)的價格)和a.fund.id =」 + Price.QUERY_PARAM_FUND_ID

別人讓我說一些事情相關來休眠JPA規範的實現。 如果您有名爲'Price'的Hibernate模型,那麼您將通過該模型執行查詢。 HQL將是這樣的

try { 
    final StringBuilder qry = new StringBuilder(); 
    qry.append(" SELECT") 
      .append(" FROM Price p") 
      .append(" WHERE p.valueDate = (SELECT MAX(pr.valueDate) FROM Price pr)") 
      .append(" AND p.fundId = :fundId"); 
    return getJpaTemplate().execute(new JpaCallback() { 
     public Object doInJpa(EntityManager em) 
       throws PersistenceException { 
      Query q = em.createQuery(qry.toString()); 
      q.setParameter("fundId", fundId); 
      return q.getResultList(); 
     } 
    }); 
} catch (RuntimeException re) {} 
+0

非常感謝這工作! – 2014-09-30 12:00:07

+0

好@AndreCoetzee玩得很開心 – 2014-09-30 12:02:28