java - SQL 到 JPQL - 半正矢公式

标签 java mysql sql jpa jpql

我有这个 SQL 查询,它从点表返回位置并按距离(以公里为单位)对它们进行排序。 该查询可以在 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 少。

因此,也许在您的情况下,创建 native 查询会更容易,然后您可以使用普通的 sql。

Query query = getEntityManager().createNativeQuery("select * from table...");
List<Object> string = query.getResultList();

关于java - SQL 到 JPQL - 半正矢公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49032962/

相关文章:

mysql - WordPress mysql 查询

c# - 如何使用SSIS包将大型数据集拆分为多个Excel电子表格?

sql - 如何在 PostgreSQL 中删除名称中包含双引号的表

sql - 计算sql查询中的持续时间总和

java - 在 Android 的 ProgressBar 上显示时间

java - AndroidAsyncHttp 错误

mysql - 在 Swift 中使用 array.append() 向数组添加值时出现问题

java - 创建计数数组的最有效方法

java - 新电脑,Eclipse 坏了

mysql - 在 Mysql 中使用 Rollup