简体   繁体   中英

How to map the result of a JpaQuery to a custom DTO?

I have a Hotspot entity class and following query which should return a List of NearHotspot objects:

Query("SELECT h, SQRT(POW(69.1 * (h.latitude - :geo_lat), 2) + POW(69.1 * (:geo_long - h.longitude) * COS(h.latitude / 57.3), 2)) AS distance FROM Hotspot h ORDER BY distance")
    List<NearHotspot> findClosestHotspots(@Param("geo_long") Double geo_long, @Param("geo_lat") Double geo_lat);

A NearHotspot object has all fields of the Hotspot object and one distance field of type Double.

@Data
@Builder
@AllArgsConstructor
public class NearHotspot {
    private Long id;
    private String name;
    private String description;
    private String category;
    private String address;
    private Integer zip;
    private String city;
    private String email;
    private String url;
    private String phone;
    private Double longitude;
    private Double latitude;
    private LocalDate createdAt;
    
    private Double distance;
}

My question now is: How to map the result of the query to List<NearHotspot> ?

I think there are two problems:

  • the response type is a List
  • the query sort of returns a Hotspot object and the distance

You are trying to return NearHotspot object and sqrt result as well in query. This won't be able to map to NearHotspot entity object because of sqrt. You would need to project your result to an interface dto because the result of the query cannot be mapped to your current object since result of query is different. Refer to blog post https://medium.com/swlh/spring-data-jpa-projection-support-for-native-queries-a13cd88ec166

Another method could be using return value List<Object[]> and mapping from List<Object[]> to NearHotspot using a mapper.

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