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

时间:2015-02-14 07:31:58

标签: java spring hibernate jpa type-conversion

我想将结果集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]设置为type但它显示空指针异常。 帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

  1. 您需要添加以下transient列:

    @Transient
    private Double distance_in_km;
    
  2. 您需要将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();