您好我正在使用以下代码从Employee表中查看firstName的列值,但是我遇到了以下错误:
错误:
线程“main”中的异常java.lang.ClassCastException:java.lang.String无法强制转换为com.servlet.prgm.Employee 在com.servlet.prgm.ManageEmployee.listEmployees(ManageEmployee.java:90) 在com.servlet.prgm.ManageEmployee.main(ManageEmployee.java:33)
代码:
Query sql = session.createQuery("select firstName FROM Employee");
List employees = sql.list();
for (Iterator iterator = employees.iterator(); iterator.hasNext(); )
{
Employee employee = (Employee)iterator.next();
employee.getFirstName();
System.out.println("First Name" +employee.getFirstName());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
Employee.class
package com.servlet.prgm;
public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
public Employee(String fname){
this.firstName=fname;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}
如果我的格式不正确,我很抱歉,我很快就会改进。
感谢您的帮助。
答案 0 :(得分:1)
您正在选择单个标量值,因此Hibernate实际上返回了一个字符串列表:
try {
Query sql = session.createQuery("select firstName FROM Employee");
List firstNames = sql.list();
for (Iterator iterator = firstNames.iterator(); iterator.hasNext(); )
{
string firstName = (string)iterator.next();
System.out.println("First Name" + firstName);
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}