简体   繁体   English

将本机查询JPA的结果集设置为POJO会引发Null指针异常

[英]setting resultset of native query JPA to POJO throws Null pointer exception

I want to convert the resultset List to entity class. 我想将结果集列表转换为实体类。 My Native query: 我的本机查询:

 @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 );

My entity class: 我的实体类:

@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;

}

service class: 服务等级:

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

Since the distance_in_km in not a variable in place entity, I am unable to map the resultset directly.The query executed successfully and Im getting response List. 由于distance_in_km不是一个可变的位置实体,因此我无法直接映射结果集。查询已成功执行并且Im正在获取响应列表。

I tried setting the pla[0] to type but It shows null pointer exception. 我尝试将pla [0]设置为输入,但显示空指针异常。 help me to resolve this issue. 帮助我解决此问题。

  1. You need to add the following transient column: 您需要添加以下transient列:

     @Transient private Double distance_in_km; 
  2. You need to change your Spring Data @Query to a Hibernate native query instead: 您需要将Spring Data @Query更改为Hibernate本机查询:

     String sql = "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} "; List<Place> places = (List<Place>) session.createSQLQuery(sql) .setParameter("latitude", latitude) .setParameter("longitute", longitute) .addEntity("p", Place.class).list(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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