我无法将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
正在填充。
任何建议?
答案 0 :(得分: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);
正试图将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);