Vinoth
Vinoth

Reputation: 63

Hibernate : How to view the query output with single column in hibernate

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.

Upvotes: 2

Views: 4907

Answers (1)

Jesse Sweetland
Jesse Sweetland

Reputation: 1614

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

Upvotes: 1

Related Questions