我得到了一份清单query.list().之后,我想在此列表中显示该对象,但我在此行中收到此错误for(Commerce[] c: this.newsList) {
java.lang.ClassCastException:[Ljava.lang.Object; 不能投[Lcom.model.Commerce; com.action.CommerceAction.searchCommerces(CommerceAction.java:35)
这是我的代码:
我的商业服务
public List<Commerce[]> getCommercesBySearch(String categorie, String lieux) {
Query query = hibUtil.getSession().createQuery("from Commerce c, Categorie ca,Lieux l "
+ "where c.categorie=ca.idCategorie and c.lieux=l.idLieux and"
+ " ca.libelle='" + categorie + "' and l.ville='" + lieux + "' ");
List<Commerce[]> tuples = (List<Commerce[]>) query.list();
return tuples;
}
Run Code Online (Sandbox Code Playgroud)
我的动作课
private CommerceService service;
private Commerce commerce = new Commerce();
private List<Commerce[]> newsList;
public String searchCommerces() {
String libelle = ServletActionContext.getRequest().getParameter("libelle");
String ville = ServletActionContext.getRequest().getParameter("ville");
this.newsList = service.getCommercesBySearch(libelle,ville);
for(Commerce[] c: this.newsList){
System.out.println(c[0].getNom());
}
if (this.newsList.size() > 0) {
return SUCCESS;
}
addActionError("Il n'existe aucun commerce de cette catégorie dans cette ville");
return ERROR;
}
Run Code Online (Sandbox Code Playgroud)
我确信这句话:
List<Commerce[]> tuples = (List<Commerce[]>) query.list();
Run Code Online (Sandbox Code Playgroud)
生成未经检查的类型转换警告.您的代码通过执行此未经检查的类型转换来污染堆. query.list()返回一个raw List,它将包含Object[].以下是相关的Hibernate文档:
将查询结果作为a返回
List.如果查询每行包含多个结果,则结果将在实例中返回Object[].
有几种方法可以解决此问题:
List<Object[]>而不是List<Commerce[]>.然后,在将list()方法的结果传递给代码的其余部分之前,可以将方法的结果转换为更可用的形式,最好是在自己的方法中.如果您需要选择的不仅仅是Commerce对象,这是更好的方法.SELECT c到查询的开头,这将允许您进行安全List<Commerce>演员.| 归档时间: |
|
| 查看次数: |
16266 次 |
| 最近记录: |