2

Hi I'm using the below code to view the column values of firstName from the table Employee but im hitting the below error:

ERROR:

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to com.servlet.prgm.Employee at com.servlet.prgm.ManageEmployee.listEmployees(ManageEmployee.java:90) at com.servlet.prgm.ManageEmployee.main(ManageEmployee.java:33)

CODE :

   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;
   }
}

Apologies if my formatting is not correct , I'm a newbie I will improve soon.

thanks for your help.

1 Answer 1

1

You're selecting a single scalar value so Hibernate is actually returning a list of strings:

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(); 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.