tags:

views:

147

answers:

3

When I am using HQL select clause following error is occuring .student is mysql table. Error: Hibernate: select studentcla0_.vStudentName as col_0_0_ from student studentcla0_ java.lang.String

Below is Code:

public static void querySubject(Session session)
     {
         String sql_query="select stud.strStudentName from StudentClass as stud";
         Query query1=session.createQuery(sql_query);

  for(Iterator it=query1.iterate();it.hasNext();)
  {
   Object[] row = (Object[]) it.next();
   System.out.println("Subject Name:"+row[0]);

  }

  return;
 }
A: 

is it hql or sql. If sql try:

session.createSQLQuery(...)
No, it's HQL - you can see the translation to SQL in the question...
David M
So I guess the exception is a ClassCast Exception on Object[] row = (Object[]) it.next();The query should return a list of String.
A: 

Just to confirm - you have a table in your database called "student" and it has a column called "vStudentName" which is a string type of some sort? The mapping is complete, and has resulted in a translation to this SQL:

select studentcla0_.vStudentName as col_0_0_
from student studentcla0_

Does this run against your database directly, or does it error there as well?

David M
A: 

When you select a single value (be it property or entity), Hibernate will return that value directly; it will not be wrapped in an Object array. See details here. So your code should be:

for(Iterator it=query1.iterate(); it.hasNext(); ) {
    System.out.println("Subject Name:"+ it.next());
}
ChssPly76