问题
I try use this HQL query:
Result.find("SELECT c, ( 3959 * acos( cos( radians(?) ) * "+
"cos( radians( c.latitude ) ) *"+
"cos( radians( c.longitude ) - radians(?) ) +"+
"sin( radians(?) ) * sin( radians( c.latitude ) ) ) ) " +
"AS distance FROM City c HAVING distance < ? ORDER BY distance ASC",
latitude, longitude, latitude, radius).fetch();
But in result:
IllegalArgumentException occured : org.hibernate.hql.ast.QuerySyntaxException: unexpected token: HAVING near line 1, column 204 [SELECT c, ( 3959 * acos( cos( radians(?) ) * cos( radians( c.latitude ) ) *cos( radians( c.longitude ) - radians(?) ) +sin( radians(?) ) * sin( radians( c.latitude ) ) ) ) AS distance FROM models.City c HAVING distance < ? ORDER BY distance ASC]
回答1:
try changing HAVING
to WHERE
, in your query.
回答2:
The keyword HAVING is only allowed if you use GROUP BY (think of having like WHERE for GROUPS). See the reference manual for SELECT syntax.
回答3:
The only way is to use a native query because :
- subselect is not possible : "Note that HQL subqueries can occur only in the select or where clauses." http://docs.jboss.org/hibernate/core/4.3/manual/en-US/html_single/#queryhql-subqueries
- having is not possible without a group by
- where is not possible neither
Java code :
@Query(value = "SELECT s.*,\n" +
" (\n" +
" 3959 * acos(\n" +
" cos(radians(s.lat))\n" +
" * cos(radians(:lat))\n" +
" * cos(radians(:lon) - radians(s.lon))\n" +
" + sin(radians(s.lat))\n" +
" * sin(radians(:lat))\n" +
" )\n" +
" ) AS distance\n" +
"FROM Stop s\n" +
"HAVING distance < 30\n" +
"ORDER BY distance asc", nativeQuery = true)
List<Stop> findClosestStops(@Param("lat") Double lat, @Param("lon") Double lon);
An alternative is to return a list of object containg the city + distance, but no where is possible, but you can limit the resultset
回答4:
Hm, what should be "?" parameter?
If true you should use it like
HAVING distance < :distance
and use
query.setParameter("distance", 50);
回答5:
try
select dis.c,dis.distance(
SELECT c,
( 3959 * acos( cos( radians(?) ) * cos( radians( c.latitude ) ) *
cos( radians( c.longitude ) - radians(?) ) + sin( radians(?) ) *
sin( radians( c.latitude ) ) ) ) AS distance FROM City c ) dis
where dis.distance<? order by dis.distance ASC
来源:https://stackoverflow.com/questions/10118449/hibernate-exception-querysyntaxexception-unexpected-token-having