Cannot writing JPQL query with subquery in FROM clause - Spring Data Jpa - Hibernate

Huỳnh Thanh Bình :

My ParkingLotEntity:

public final class ParkingLotEntity {

    @Id
    @Column(name = "[ID]", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "[PARKING_LOT_TYPE_ID]", referencedColumnName = "[ID]", nullable = false)
    private ParkingLotTypeEntity parkingLotTypeEntity;

    @Column(name = "[LATITUDE]", nullable = false)
    private Double latitude;

    @Column(name = "[LONGITUDE]", nullable = false)
    private Double longitude;

    @Column(name = "[OPENING_HOUR]", nullable = false)
    private Time openingHour;

    @Column(name = "[CLOSING_HOUR]", nullable = false)
    private Time closingHour;

    @ColumnDefault("true")
    @Column(name = "[IS_AVAILABLE]")
    private Boolean isAvailable;

    @Column(name = "[LAST_UPDATED]")
    private Timestamp lastUpdated;

    @Version
    private Long version;
}

My Jpa Repository Interface

@Repository
public interface ParkingLotRepository extends JpaRepository<ParkingLotEntity, Long> {

    @Lock(LockModeType.OPTIMISTIC)
    @Query("SELECT P " +
            "FROM ParkingLotEntity P " +
            "WHERE P.latitude BETWEEN ?3 AND ?1 " +
            "AND P.longitude BETWEEN ?4 AND ?2 " +
            "AND FUNCTION('CONVERT', TIME, FUNCTION('CURRENT_TIME')) BETWEEN P.openingHour AND P.closingHour " +
            "AND P.isAvailable = TRUE")
    List<ParkingLotEntity> getAllParkingLotCurrentlyWorkingInRegion(
            double top,     // north limit
            double right,   // east limit
            double bottom,  // south limit
            double left);   // west limit


    @Lock(LockModeType.OPTIMISTIC)
    @Query("SELECT P " +
            "FROM ParkingLotEntity P " +
            "WHERE FUNCTION('dbo.GET_DISTANCE_IN_KILOMETRE', ?1, ?2, P.latitude, P.longitude) <= ?3 " +
            "AND FUNCTION('CONVERT', TIME, FUNCTION('CURRENT_TIME')) BETWEEN P.openingHour AND P.closingHour " +
            "AND P.isAvailable = TRUE")
    List<ParkingLotEntity> getAllParkingLotCurrentlyWorkingInRegionOfRadius(
            double latitude,            // target location's latitude
            double longitude,           // target location's longitude
            short radiusInKilometre);   // radius in kilometre to scan
}

The 2 methods above run good, but the problem is that I also need the distance between any parking lot from the result set to the location at 2nd method "getAllParkingLotCurrentlyWorkingInRegionOfRadius" ! and the distance had been already calculated by my define function in SQL server. The result set from method 2 is a success but without Distance returned back (which is my need), just a set of parkingLotEntity only!

I try to write a native query in SQL Server. My approach is using subquery together with join, as the code below:

SELECT P.*, DISTANCE
FROM PARKING_LOT P INNER JOIN (
    SELECT PL.ID, dbo.GET_DISTANCE_IN_KILOMETRE(10.784122211291663, 106.71152489259839, PL.LATITUDE, PL.LONGITUDE) AS DISTANCE
    FROM PARKING_LOT PL) AS PL 
ON P.ID = PL.ID AND DISTANCE <= 10
AND CONVERT(TIME, GETDATE()) BETWEEN P.OPENING_HOUR AND P.CLOSING_HOUR 

Here is my define function in SQL Server:

CREATE FUNCTION [dbo].[GET_DISTANCE_IN_KILOMETRE](
    @LAT1 FLOAT, /* POINT1.LATITUDE */
    @LNG1 FLOAT, /* POINT1.LONGITUDE */
    @LAT2 FLOAT, /* POINT2.LATITUDE */
    @LNG2 FLOAT) /* POINT2.LONGITUDE */
RETURNS SMALLINT
AS
BEGIN
    DECLARE @DEGTORAD FLOAT
    DECLARE @ANS FLOAT
    DECLARE @KILOMETRE FLOAT

    SET @DEGTORAD = 57.29577951
    SET @ANS = 0
    SET @KILOMETRE = 0

    IF @LAT1 IS NULL OR @LAT1 = 0 OR 
        @LNG1 IS NULL OR @LNG1 = 0 OR 
        @LAT2 IS NULL OR @LAT2 = 0 OR
        @LNG2 IS NULL OR @LNG2 = 0

        BEGIN
            RETURN @KILOMETRE
        END

    SET @ANS = SIN(@LAT1 / @DEGTORAD) * SIN(@LAT2 / @DEGTORAD) + COS(@LAT1 / @DEGTORAD) * COS(@LAT2 / @DEGTORAD) * COS(ABS(@LNG2 - @LNG1)/@DEGTORAD)
    SET @KILOMETRE = 6371 * ATAN(SQRT(1 - SQUARE(@ANS)) / @ANS)

    RETURN CEILING(@KILOMETRE)
END

Sample result of this query: (except column distance recently joined, all other fields belong to ParkingLotEntity)

ID  PARKING_LOT_TYPE_ID LATITUDE    LONGITUDE   OPENING_HOUR       CLOSING_HOUR     IS_AVAILABLE    LAST_UPDATED    VERSION DISTANCE
56  1                   10.798351   106.696676  00:00:00.0000000    20:30:00.0000000    1        2020-02-20 23:57:00    0   3
57  1                   10.73789    106.723666  00:00:00.0000000    23:00:00.0000000    1        2020-02-20 23:57:00    0   6
58  1                   10.740738   106.704265  00:00:00.0000000    21:30:00.0000000    1        2020-02-20 00:03:00    0   5
67  1                   10.771154   106.671152  00:00:00.0000000    22:00:00.0000000    1        2020-02-20 00:12:00    0   5

The query runs good in a native query, but I cannot implement it on my spring boot program by using JPQL.

I search for some resource and it said that JPQL cannot use a subquery in FROM clause.

Also, I have try to use native query in JPQL @Query, but it seem no work! and I do not know if I return the right datatype or not.

Please let me know how can I select all field from my ParkingLotEntity and for each row in result set, calculate the distance to a specific coordinate by the function above, join the 'distance' column to the result set, and then return to the spring server by using Hibernate/JPA/JPQL/... query? I need the distance to return to server very much.

Andronicus :

It's not possible in jpql. Take a look at the documentation. It says:

Subqueries may be used in the WHERE or HAVING clause.

You can use Query with native parameter set to true or other solutions, like EntityManager#createNativeQuery.

But to do that, you would have to provide a mapping. ParkingLotEntity does not have a distance field and returning two entities from a query is not possible. You would have to query for Object[] or Tuple. See here for more information.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=418005&siteId=1