Hello, I'm in a project that uses geolocation and I'm doing a feature to list the stores closest to the location chosen by the user. I'm using the PostgreSQL database and did this query to perform the search:
SELECT ID, CIDADE, CNPJ, DESCRICAO, EMAIL, ENDERECO, LAT, LON, NOME,
TELEFONE
FROM (
SELECT ID, CIDADE, CNPJ,DESCRICAO, EMAIL, ENDERECO, LAT, LON, NOME, TELEFONE,
(6371 * acos(
cos( radians(latitude_local_usuario) )
* cos( radians( loja.lat ) )
* cos( radians( loja.lon ) - radians(longitude_local_usuario) )
+ sin( radians(latitude_local_usuario) )
* sin( radians( loja.lat ) )
)
) AS distancia
FROM loja
) x
GROUP BY ID, CIDADE, CNPJ, DESCRICAO, EMAIL, ENDERECO, LAT, LON, NOME, TELEFONE, DISTANCIA
HAVING DISTANCIA < distacia_raio_usuario
ORDER BY DISTANCIA ASC;
With this query I can perform the search perfectly executing it directly in the database. By java I'm doing it like this:
TypedQuery<Estudio> query = this.manager
.createQuery("select ID, CIDADE, CNPJ, DESCRICAO, EMAIL, ENDERECO, LAT, LON, NOME, TELEFONE"
+ "FROM ("
+ "select ID, CIDADE, CNPJ,DESCRICAO, EMAIL, ENDERECO, LAT, LON, NOME, TELEFONE,"
+ "(6371 * acos(" + "cos( radians(:lat) )" + "* cos( radians( loja.lat ) )"
+ "* cos( radians( loja.lon ) - radians(:lon) )" + "+ sin( radians(:lat) )"
+ "* sin( radians( loja.lat ) ) " + ")" + ") AS distancia"
+ "FROM loja) x"
+ "GROUP BY ID, CIDADE, CNPJ, DESCRICAO, EMAIL, ENDERECO, LAT, LON, NOME, TELEFONE, DISTANCIA"
+ "HAVING DISTANCIA < 5" + "ORDER BY DISTANCIA ASC;", Loja.class);
query.setParameter("lat", lat);
query.setParameter("lon", lon);
return query.getResultList();
However, I'm getting the following error:
ERROR [org.hibernate.hql.internal.ast.ErrorCounter] (default task-18) line 1:84: unexpected token: select: line 1:84: unexpected token: select
I do not know why the error, but running the query below works normally:
TypedQuery<Estudio> query = this.manager.createQuery("select l from Loja l",
Loja.class);