【问题标题】:classcast exception on spring-data-jpa dtospring-data-jpa dto 中的 classcastexception
【发布时间】:2017-07-27 11:26:33
【问题描述】:

我无法将 JPA ResultSet 转换为 DTO。当我从数据库中获取值,但使用 toString() 方法打印值时,我得到了 ClassCastException:

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 正在被填充。

有什么建议吗?

【问题讨论】:

  • cityListingresponseCityList的类型是什么?
  • 两者的类型都是List&lt;CityEntity&gt; cityListing
  • 我猜问题出在您在查询中返回a.countrycode 的位置,它返回的是整个 CountryEntity 对象。

标签: java spring spring-data-jpa


【解决方案1】:

此查询将返回List&lt;Object[]&gt;

@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); 正在尝试将 s 转换为 CityEntity 并且失败了。

请将您的查询更新为此。

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

【讨论】:

  • 感谢您的回答,但我不希望在我的 api 响应中选择国家代码。
  • 您可以使用多种方法来做到这一点。您可以在查询后处理列表以创建您自己的 POJO,您可以在查询中使用 new 运算符直接引用您的 POJO 上的构造函数,或者您可以使用EntityGraph。还有几个可以实现您的目标。
猜你喜欢
  • 2016-09-03
  • 2018-03-05
  • 2016-01-26
  • 2017-11-29
  • 2016-03-08
  • 2021-05-08
  • 2017-07-17
  • 1970-01-01
  • 2012-03-08
相关资源
最近更新 更多