2

こんにちは、以下のコードを使用して、テーブル Employee から firstName の列の値を表示していますが、以下のエラーが発生しています。

エラー:

スレッド「メイン」の例外 java.lang.ClassCastException: java.lang.String は com.servlet.prgm.ManageEmployee.listEmployees(ManageEmployee.java:90) の com.servlet.prgm.Employee にキャストできません。 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;
   }
}

私のフォーマットが正しくない場合はお詫びします。私は初心者です。すぐに改善します。

ご協力いただきありがとうございます。

4

1 に答える 1

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(); 
}
于 2013-06-04T17:20:25.990 に答える