gpt4 book ai didi

java - 将 native 查询 JPA 的结果集设置为 POJO 抛出空指针异常

转载 作者:太空宇宙 更新时间:2023-11-04 14:09:25 25 4
gpt4 key购买 nike

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

 @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] 设置为类型,但它显示空指针异常。帮我解决这个问题。

最佳答案

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

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

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

关于java - 将 native 查询 JPA 的结果集设置为 POJO 抛出空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28513517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com