2017-07-27 103 views
-1

我無法將JPA ResultSet轉換爲DTO。雖然我正在從數據庫值,但使用toString()方法印製的價值觀,我得到ClassCastException異常:spring-data-jpa上的classcast異常dto

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; 
    } 
} 

在調試,我發現cityListing越來越填充。

有什麼建議嗎?

+0

「cityListing」和「responseCityList」的類型是什麼? –

+0

都是類型'列表 city列出' – 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);試圖投sCityEntity和失敗。

請更新您的查詢。

@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

感謝您的回答,但我不希望countrycode在我的api響應中被選中。 – Ankit

+0

有多種方法可以用來做到這一點。您可以在查詢後處理列表以創建您自己的POJO,您可以使用查詢中的新運算符直接引用POJO上的構造函數,也可以使用「EntityGraph」。還有幾個要完成你的目標。 – ryan2049