Java 将本机查询JPA的resultset设置为POJO会引发空指针异常
我想将结果集列表转换为实体类。 我的本机查询:Java 将本机查询JPA的resultset设置为POJO会引发空指针异常,java,spring,hibernate,jpa,type-conversion,Java,Spring,Hibernate,Jpa,Type Conversion,我想将结果集列表转换为实体类。 我的本机查询: @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(latitud
@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 );
服务类别:
List<Object[]> places = Repository.findBylattitudeAndlongitute(latitude, longitute);
Place place = null;
for (Object[] pla:places)
{
place.setType((String) pla[0]);
place.setName((String) pla[1]);
}
由于距离(单位:km)不是一个变量实体,我无法直接映射结果集。查询已成功执行,我正在获取响应列表
我尝试将pla[0]设置为type,但它显示空指针异常。
帮我解决这个问题
您需要添加以下瞬态列:
您需要将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();
@Transient
private Double distance_in_km;
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();