2017-07-27 37 views
-1

JPA ResultSetをDTOにキャストできません。デバッグは、私はcityListingを取得していることが判明している間spring-data-jpaのクラスキャスト例外

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.practice.entity.CityEntity 
    at java.util.ArrayList.forEach(Unknown Source) ~[na:1.8.0_91] 
    at com.practice.service.CityService.getCities(CityService.java:47) ~[classes/:na] 

@Service 
public class CityService { 
..... 

      cityListing = cityDAO.citylisting(countryName); 

      cityResponse.setCityCount(cityListing.size()); 


    cityListing.forEach(s -> { 
       System.out.println(s); 
       responseCityList.add(s); 
      }); 

@Repository("cityDAO") 
public interface CityManipulationDAO extends JpaRepository<CityEntity, Integer>{ 

    @Query("Select a.id, a.name, a.district,a.countrycode, a.population from CityEntity a where a.countrycode.CountryName=:countryName") 
    //List of cities for particular countries 
    public List<CityEntity> citylisting(@Param("countryName") String Name); 

} 

@Entity 
@Table(name="city") 
public class CityEntity { 

    @Id 
    private Integer id; 

    @Column 
    private String name; 

    @ManyToOne(optional=true, fetch=FetchType.LAZY) 
    @JoinColumn(name="countrycode", referencedColumnName="code") 
    private CountryEntity countrycode; 

    @Column 
    private String district; 

    @Column 
    private Integer population; 
... 

    @Override 
    public String toString() { 
     return id+","+name+","+district+","+population; 
    } 
} 

:私は、toString()メソッドを使用してデータベースの値が、印刷の値を取得していますが、私はClassCastExceptionが取得しています人口が多い。

何か提案がありますか?

+0

「cityListing」と「responseCityList」の種類は何ですか? –

+0

はどちらも 'List cityListing'です – Ankit

+0

質問に' a.countrycode'を返すところに問題があると思います。そこにはCountryEntityオブジェクト全体が返されています。 –

答えて

1

このクエリはList<Object[]>を返します。

@Query("Select a.id, a.name, a.district,a.countrycode, a.population from CityEntity a where a.countrycode.CountryName=:countryName") 
//List of cities for particular countries 
public List<CityEntity> citylisting(@Param("countryName") String Name); 

私はresponseCityList.add(s);CityEntitysをキャストしようとすると失敗していることを、あなたのスタックトレースのオフに基づいて考えています。

これにクエリを更新してください。

@Query("Select a from CityEntity a where a.countrycode.CountryName=:countryName") 
//List of cities for particular countries 
public List<CityEntity> citylisting(@Param("countryName") String Name); 
+0

あなたの答えをありがとうが、私は私のapiの応答で国コードを選択したくありません。 – Ankit

+0

これには複数の方法があります。クエリの後にリストを処理して独自のPOJOを作成することができます。クエリ内のnew演算子を使用してPOJOのコンストラクタを直接参照することも、 'EntityGraph'を使うこともできます。あなたの目標を達成するにはいくつかの方法があります。 – ryan2049

関連する問題