简体   繁体   中英

How to map from JPA Object in spring boot

good day all: I have a little issue I want you help me to resolve. My problem is the next, I have to find the shorter distance of the stores according to google maps and according the latitude and longitude, anyway, I have the query that do these, my problem is when I call to jparepository it returns an array and I need to return me with a specific format.

This is my end-point I'm trying to get from jparepository

@RequestMapping(value = "api/promos/distance/", method = RequestMethod.GET)
public ResponseEntity<?> distance(@RequestParam(required = false) Double latitude, Double longitude, Long radius) {
    try {
        return ResponseEntity.status(HttpStatus.OK)
                .body(locationDAO.findDistance(latitude,longitude,radius));

    } catch (Exception ex){
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.toString());
    }
}

this is my repository with the params and return 2 values

@Query(value = "select sp.id as id, \n" +
            "          ( 6371  * acos( cos( radians(:latitude) ) \n" +
            "      * cos( radians( sp.latitude )) \n" +
            "      * cos( radians( sp.longitude ) - radians(:longitude)) \n" +
            "      + sin( radians(:latitude) ) \n" +
            "      * sin( radians( sp.latitude ) ) ) ) AS distance \n" +
            "        from promo_locations sp \n" +
            "having distance < :radius ORDER BY distance ASC", nativeQuery = true)
    List<Object> findDistance(
            @Param("latitude") Double latitude,
            @Param("longitude") Double longitude,
            @Param("radius") Long radius);

and it show me this

[
    [
        1,
        137.94383549078196
    ],
    [
        2,
        137.94383549078196
    ]
]

but I need to show me in this format:

[
    {
        "id" : 1,
        "distance" : 137.94383549078196
    },
    {
        "id" : 2,
        "distance" :137.94383549078196
    }
]

If someone knows how to map or how to convert I will thank you so much

take a look at this and this
basically you need to define SqlResultSetMapping for your native query

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM