简体   繁体   中英

Convert mysql query to JPQL query

How can i state the following mysql query in JPQL

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

what i have tried is the following:

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

but get errors on that approach :

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"

I think it will work if you will added bracket before and after sub-query like.

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

else let me say some thing related to hibernate implementation of JPA Specification. If you have Hibernate model named 'Price' and you are going to do query through that model then. the HQL will be like that

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) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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