java.lang.ClassCastException: com.imooc.model.Commodity cannot be cast to [Ljava.lang.Object;
測(cè)試代碼如下
@Test
public void testWhere3() {
String hql = "from Commodity c";
Query query = session.createQuery(hql);
List<Object[]> list = query.list();
for (Object[] objects : list) {
System.out.println("id:" + objects[0]);
}
}
實(shí)體類代碼:
package com.imooc.model;
import java.io.Serializable;
public class Commodity implements Serializable {
private Long id;//主鍵
private String name;//名稱
private Double price;//價(jià)格
private String unit;//單位
private String category;//類別
private String description;//簡(jiǎn)介
private Seller seller;//商家
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Seller getSeller() {
return seller;
}
public void setSeller(Seller seller) {
this.seller = seller;
}
@Override
public String toString() {
return "Commodity [id=" + id + ", name=" + name + ", price=" + price + ", unit=" + unit + ", category="
+ category + ", description=" + description + ", seller=" + seller + "]";
}
public Commodity() {
super();
}
public Commodity(Long id, String name, Double price, String unit, String category, String description,
Seller seller) {
super();
this.id = id;
this.name = name;
this.price = price;
this.unit = unit;
this.category = category;
this.description = description;
this.seller = seller;
}
public Commodity(String name) {
super();
this.name = name;
}
}
2018-01-10
這個(gè)老師已經(jīng)講過了。只有一個(gè)數(shù)據(jù)時(shí)使用List<Object> list = query.list();多個(gè)數(shù)據(jù)才可以使用你所寫的數(shù)組形式,這是它本身的一個(gè)機(jī)制。記住就行了
2018-01-09
你創(chuàng)建的實(shí)體類類型跟Object不匹配,沒法轉(zhuǎn)換。
第四行改為Query query = session.createSQLQuery(hql).addEntity(Stock.class);
2018-01-09
經(jīng)過幾次試驗(yàn),發(fā)現(xiàn)不能查詢單個(gè)字段,改成查多個(gè)字段,成功了
String hql = "select c.name,c.price from Commodity c";
Query query = session.createQuery(hql);
List<Object[]> list = query.list();
for (Object[] objects : list) {
System.out.println("name:" + objects[0]);
System.out.println("price:" + objects[1]);
}
---------------------------------------執(zhí)行結(jié)果----------------------------
Hibernate:?
? ? select
? ? ? ? commodity0_.NAME as col_0_0_,
? ? ? ? commodity0_.PRICE as col_1_0_?
? ? from
? ? ? ? COMMODITY commodity0_
name:玩具人偶
price:1500.0
name:鴨脖
price:15.0
name:臘腸
price:200.0