Paulius Matulionis
Paulius Matulionis

Reputation: 23415

Convert MySql query to JPA named query

I have a MySql query like this:

select AK.*, max(AA.activityDate) 
from AssessmentKey AK 
join AssessmentActivity AA on AA.ASSESSMENTKEY_ID = AK.id 
group by AK.id having max(AA.activityDate) <=  '2012-10-02 17:30:55'

Is there a way to convert into in JPA NamedQuery. I am using OpenJPA.

If I put it directly into:

@NamedQuery(name = "AssessmentActivity.findByDate", 
  query = "select AK.*, max(AA.activityDate) from AssessmentKey AK 
           join AssessmentActivity AA on AA.ASSESSMENTKEY_ID = AK.id 
           group by AK.id having max(AA.activityDate) <=  '2012-10-02 17:30:55'")

The error is showed here: select AK.* that identifier expected, got "*" and also it does not like on, here it says:

enter image description here

How can I resolve this problem?

Upvotes: 0

Views: 2001

Answers (1)

szegedi
szegedi

Reputation: 873

First problem: you should replace AK.* with AK you just need the entity alias here.

Second problem: join syntax is not like that. You should write: join and navigate through the object references,eg: AK.assesmentActivity and use the where keyword instead of on

Here's a tip on join: JPQL join

Remember: you are in the ORM, dealing with Entities and their properties, not DB foreign keys and columns.

(ps: Maybe you wanted to write a NativeQuery? There you can use native SQL syntax)

EDIT: (on your comment) So you must start your query from AA:

select AK from AssesmentActivity AA join AssesmentKey AK where AA.assesmentKey = AK ...

This way you can join them.

Upvotes: 2

Related Questions