将mysql查询转换为JPQL查询

时间:2014-09-30 11:10:32

标签: java mysql jpa jpql

如何在JPQL中声明以下mysql查询

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"

1 个答案:

答案 0 :(得分:0)

我认为如果你在子查询之前和之后添加括号,它会起作用。

&#34;从价格a中选择一个a.valueDate =(从价格中选择MAX(a.valueDate))和a.fund.id =:&#34; + Price.QUERY_PARAM_FUND_ID

否则让我说一些与JPA规范的hibernate实现相关的事情。 如果你有Hibernate模型名为&#39; Price&#39;然后你将通过该模型进行查询。 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) {}