我有一个DAO类,我使用HQL从我的数据库中获取数据
public List<Booking> getInventory(){
Session session = sessionFactory.openSession();
session.beginTransaction();
Query query = session.createQuery("select booking.bookingId, booking.customerId, booking.vehicleId, booking.section, booking.isle, booking.row from Booking booking");
List<Booking> invList = (List<Booking>) query.getResultList();
return invList;
}
我正在尝试访问此处返回的对象
@RequestMapping("/")
public String home(Model model){
DAO dao = new DAO();
List<Booking> invList = (List<Booking>) dao.getInventory();
for(Booking booking : invList){
System.out.println(booking.getBookingId());
}
return "home";
}
但我收到此错误
Request processing failed; nested exception is java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.algonquinstorage.beans.Booking
我不知道为什么我会收到此错误,有人可以帮助我吗?
编辑:
这是我的预订课程
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Booking implements Serializable {
@Id
int bookingId;
int vehicleId;
int customerId;
String section;
int isle;
int row;
public int getBookingId() {
return bookingId;
}
public void setBookingId(int bookingId) {
this.bookingId = bookingId;
}
public int getVehicleId() {
return vehicleId;
}
public void setVehicleId(int vehicleId) {
this.vehicleId = vehicleId;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public int getIsle() {
return isle;
}
public void setIsle(int isle) {
this.isle = isle;
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public Booking() {
super();
}
public Booking(int bookingId, int customerId, int vehicleId, String section, int isle, int row) {
super();
this.bookingId = bookingId;
this.customerId = customerId;
this.vehicleId = vehicleId;
this.section = section;
this.isle = isle;
this.row = row;
}
}
答案 0 :(得分:1)
您必须将DAO功能更改为:
public List<Booking> getInventory(){
Session session = sessionFactory.openSession();
session.beginTransaction();
Query query = session.createQuery("select booking from Booking booking");
List<Booking> invList = (List<Booking>) query.getResultList();
return invList;
}
查询
select booking.bookingId, booking.customerId, booking.vehicleId, booking.section, booking.isle, booking.row from Booking booking
不会返回List<Booking>
,而是List<Object[]>
,其中每个Object[]
是一个包含[bookingId,customerId,vehicleId,section,isle,row]的数组