我在尝试使用Hibernate执行SQL查询时遇到以下错误。
错误: -
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to model.Emp1000
at com.firsthb.StoreData.selectoperation_sql(StoreData.java:107)
at com.firsthb.StoreData.main(StoreData.java:43)
Hibernate代码: -
Query sqlquery1 = session.createSQLQuery("Select a.id, a.firstName, a.lastName, b.emp_dept from Emp1000 a inner join emp_dept b on a.id = b.emp_id");
List<Emp1000> sqllist1 = sqlquery1.list();
for (Emp1000 emp : sqllist1) {
System.out.println(emp.getFirstName());
}
员工持久类: -
package model;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the emp1000 database table.
*
*/
@Entity
@NamedQuery(name="Emp1000.findAll", query="SELECT e FROM Emp1000 e")
public class Emp1000 implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String firstName;
private String lastName;
//bi-directional many-to-one association to EmpDept
@OneToMany(mappedBy="emp1000", cascade = CascadeType.MERGE)
private List<EmpDept> empDepts;
public Emp1000() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<EmpDept> getEmpDepts() {
return this.empDepts;
}
public void setEmpDepts(List<EmpDept> empDepts) {
this.empDepts = empDepts;
}
public EmpDept addEmpDept(EmpDept empDept) {
getEmpDepts().add(empDept);
empDept.setEmp1000(this);
return empDept;
}
public EmpDept removeEmpDept(EmpDept empDept) {
getEmpDepts().remove(empDept);
empDept.setEmp1000(null);
return empDept;
}
}
问题: -
持久化类Emp1000与查询执行完全匹配。为什么我会收到错误
答案 0 :(得分:0)
我认为EmpDept
是另一个实体。
您无法使用表格Emp1000
emp_dept
尝试做类似的事情:
Select a.id, a.firstName, a.lastName, b.department from Emp1000 a inner join EmpDept b on a.id = b.id;
答案 1 :(得分:0)
在您的查询中,您尝试获取
Select a.id, a.firstName, a.lastName, b.emp_dept from Emp1000 a inner join emp_dept b on a.id = b.emp_id
实际上是返回两个不同对象的属性。你想要的是来自两个不同实体的自定义字段。您可以使用此
实现此目的Query query = session.createQuery("Select a.id, a.firstName, a.lastName, b.emp_dept from Emp1000 a inner join emp_dept b on a.id = b.emp_id");
List<Object[]> rows = query.list();
然后迭代这个Object []列表,如下所示:
for (Object[] row: rows) {
System.out.println(" ------------------- ");
System.out.println("id: " + row[0]);
System.out.println("first name: " + row[1]);
System.out.println("last name: " + row[2]);
System.out.println("department: " + row[3]);
}
您收到此错误是因为它尝试将object []转换为特定的Entity对象。