簡體   English   中英

將本機查詢JPA的結果集設置為POJO會引發Null指針異常

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

我想將結果集列表轉換為實體類。 我的本機查詢:

 @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不是一個可變的位置實體,因此我無法直接映射結果集。查詢已成功執行並且Im正在獲取響應列表。

我嘗試將pla [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(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM