2017-07-27 82 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