将原生查询JPA的ResultSet设置为POJO会抛出NullPointerException

问题描述 投票:0回答:1

我想将结果集List转换为实体类。 我的本机查询:

 @Query("select type,name,latitude,longitute,111.045* DEGREES (ACOS(COS(RADIANS(:latitude))*COS (RADIANS(latitude))*COS(RADIANS(:longitute) - RADIANS (longitute))"
            + "+SIN (RADIANS (:latitude))*SIN (RADIANS(latitude)))) As distance_in_km from Place ORDER BY distance_in_km ")
     List<Object[]> findBylattitudeAndlongitute(@Param("latitude") double latitude ,@Param("longitute") double longitute );

我的实体类:

@EnableCaching
@Entity
@Table(name = "PLACEDETAILS_H")
public class Place {

    public Place() {
    }   
    private String type;
    private String name;
    private String Code;
    private String Name;
    private String Code1;   
    private String Name2;
    private double latitude;
    private double longitute;

}

服务等级:

 List<Object[]>  places = Repository.findBylattitudeAndlongitute(latitude, longitute);  
Place place = null;
for (Object[] pla : places) {
    place.setType((String) pla[0]);
    place.setName((String) pla[1]); 
}

由于 distance_in_km 不是变量实体,我无法直接映射结果集。查询执行成功,我正在获取响应列表

我尝试将 pla[0] 设置为类型,但它显示空指针异常。 帮我解决这个问题。

java spring hibernate jpa type-conversion
1个回答
0
投票
  1. 您需要添加以下

    transient
    列:

     @Transient
     private Double distance_in_km;
    
  2. 您需要将 Spring Data @Query 更改为 Hibernate 本机查询:

     List<Place> places = (List<Place>) session.createSQLQuery("""
         select 
             type as {p.type}, 
             name as {p.name}, 
             latitude as {p.latitude}, 
             longitute as {p.longitute},
             111.045* DEGREES (
                 ACOS(
                     COS(RADIANS(:latitude)) * 
                     COS (RADIANS(latitude)) *
                     COS(RADIANS(:longitute) - RADIANS (longitute)) +
                     SIN (RADIANS (:latitude))*SIN (RADIANS(latitude)))
             ) As {p.distanceInKm} 
         from Place p 
         ORDER BY {p.distanceInKm}
         """
     )
     .setParameter("latitude", latitude)
     .setParameter("longitute", longitute)
     .addEntity("p", Place.class)
     .list();
    
© www.soinside.com 2019 - 2024. All rights reserved.