问题
Possible Duplicate:
SQL Query with MySQL
I implement a Rest Web Service (JAX-RS) using Jersey in Java. I use hibernate to fetch the data from MySQL database. With this query:
(Select distinct deliverable.id from Task as t where t.project.id= :id And t.user.username = :name order by t.id desc")
.setMaxResults(3)
.setLong("id", projectId)
.setString("name", username)
.list();
I have a right result which is : [275,51,286]. This is the provided key for every id in the database:
id key
---------------------
275 2.0
51 cm
286 19.87
Now I use this query (Everything is the same except deliverable.key instead of deliverable.id) :
(Select distinct deliverable.key from Task as t where t.project.id= :id And t.user.username = :name order by t.id desc")
.setMaxResults(3)
.setLong("id", projectId)
.setString("name", username)
.list();
The result is: ["2.0","19.88","19.99"]. The first one is right, but the second and third one are completely different keys.
Maybe it can be solved by "alias" or any other way. your suggestion?
回答1:
I found the answer:
("select d.key from Deliverable as d, Task as t
where t.deliverable.id = d.id and
t.id = (select max(t1.id) from Task t1 where t1.deliverable.id = d.id)
and d.project.id= :id
and t.user.username = :name
order by t.id desc")
.setMaxResults(3)
.setLong("id", projectId)
.setString("name", username)
.list();
来源:https://stackoverflow.com/questions/11457292/sql-query-using-hibernate-in-a-restful-web-service