سؤال

why do this query works directly on postgres database:

select m from medicine_case m WHERE m.id IN (select m.id  FROM medicine_case m  LEFT OUTER JOIN patient ON m.patient=patient.id  ORDER BY patient.surname ASC )

AND in OpenJpa with the exact corresponding typed query:

String sql = " select m from medicine_case m WHERE m.id IN (select m.id  FROM medicine_case m  LEFT OUTER JOIN "
                + "patient ON m.patient=patient.id  ORDER BY patient.surname ASC )";
        TypedQuery<MedicineCase> query = persistenceClient.createQueryMC(sql);
        setParameter(query);
        query.setFirstResult(first);
        query.setMaxResults(count);

gives me:

org.apache.openjpa.persistence.ArgumentException: Encountered "m . id IN ( select m . id FROM medicine_case m LEFT OUTER JOIN patient ON" at character 37, but expected: ["(", ")", "*",.... etc etc

why????? it's so strange and makes me crazy!

the code that creates the query from entity manager:

return entityManager.createQuery(sql, MedicineCase.class);

and the code that executes it:

return query.getResultList().iterator();

هل كانت مفيدة؟

المحلول

You're confusing SQL (which is what PostgreSQL expects) and HQL (which is what EntityManager.createQuery() expects).

Those are two different languages. SQL works with tables and columns, whereas JPQL works with JPA entities, fields/properties and associations, and is translated by your JPA implementation into SQL.

If you want to execute SQL, you must use EntityManager.createNativeQuery().

نصائح أخرى

in jpql it becomes a bit different:

String sql = "select m from " + MedicineCase.class.getSimpleName() + " m WHERE m.id IN :mcList";
TypedQuery<MedicineCase> query = persistenceClient.createQueryMC(sql);
        query.setParameter("mcList", persistenceClient.executeQueryMCId(persistenceClient.createQueryMCId(createSql()
                + addOrders())));
        setParameter(query);
        query.setFirstResult(first);
        query.setMaxResults(count);
        return persistenceClient.executeQueryMC(query);

where createSql returns:

sql.append("select m.id ").append(" FROM ").append(MedicineCase.class.getSimpleName()).append(" m");

and addOrders:

" LEFT OUTER JOIN m.patient p ORDER BY p.surname ASC
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top