SQL到JPQL - 哈希因公式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL到JPQL - 哈希因公式相关的知识,希望对你有一定的参考价值。
我有这个SQL查询,它从点表返回位置,并以km为单位按距离排序。该查询适用于SQL,但我在将其转换为JPQL时遇到一些困难。我暂时使用静态值使其更容易阅读。
SQL - 有效
SELECT DISTINCT *,( 6371 * acos( cos( radians(60.1733) ) * cos( radians( spot.spot_latitude ))
* cos( radians(spot.spot_longitude) - radians(24.941)) + sin(radians(60.1733))
* sin( radians(spot.spot_latitude)))) AS distance
FROM spot
WHERE spot_id = spot_id
HAVING distance < 10
ORDER BY distance
JPQL - 不起作用
SELECT DISTINCT s, ( 6371 * acos( cos( radians(60.1733) ) * cos( radians( spot.spot_latitude ))
* cos( radians(spot.spot_longitude) - radians(24.941)) + sin(radians(60.1733))
* sin( radians(spot.spot_latitude)))) AS distance
FROM spot
WHERE s.spot_id = s.spot_id
HAVING distance < 10
ORDER BY s.distance
JPQL根本原因抛出两个异常:
A MultiException has 2 exceptions. They are:
1. org.eclipse.persistence.exceptions.PersistenceUnitLoadingException:
Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: ParallelWebappClassLoader
context: skatebayBackend
delegate: false
----------> Parent Classloader:
java.net.URLClassLoader@2f2c9b19
Internal Exception: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [skatebay_pu] failed.
Internal Exception: Exception [EclipseLink-7158] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Error encountered when building the @NamedQuery [Spot.getSpotsInMyArea] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata].
Internal Exception: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable
2. java.lang.IllegalStateException: Unable to perform operation: create on rest.SpotApi
答案
JPQL适用于实体,而不适用于数据库表。这里至少有两个选项:
确保将实体映射到表并使用正确的查询语法。但是,JPQL提供的可能性比SQL少。 因此,在您的情况下,创建本机查询会更容易,然后您可以使用普通的sql。
Query query = getEntityManager().createNativeQuery("select * from table...");
List<Object> string = query.getResultList();
另一答案
您在where子句中使用JPQL中的别名s
,而是执行此操作。
SELECT DISTINCT s, ( 6371 * acos( cos( radians(60.1733) ) * cos( radians( spot.spot_latitude ))
* cos( radians(spot.spot_longitude) - radians(24.941)) + sin(radians(60.1733))
* sin( radians(spot.spot_latitude)))) AS distance
FROM spot AS s
WHERE s.spot_id = s.spot_id
HAVING distance < 10
ORDER BY s.distance
以上是关于SQL到JPQL - 哈希因公式的主要内容,如果未能解决你的问题,请参考以下文章
JPQL 到 SQL 使用 Hibernate 更新查询交叉连接问题