yashpal bharadwaj yashpal bharadwaj - 7 months ago 595
Java Question

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to className

Code:

public void getDetails() {
try {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
String hql = "select c.mobile, c.password FROM CrbtSubMasterDemo c where rownum<20";
Query query = session.createQuery(hql);
List<CrbtSubMasterDemo> itr = query.list();
session.getTransaction().commit();
for (CrbtSubMasterDemo pojo : itr) {//excepion line
System.out.println("[" + pojo.getMobile() + "]");
}
} catch (Exception e) {
e.printStackTrace();
}
}


CrbtSubMasterDemo is pojo mapped with the db.
When I try to run it, it gives following Exception:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.telemune.demoPojo.CrbtSubMasterDemo
at com.telemune.demoHibernate.QueryTester.getDetails(QueryTester.java:57)
at com.telemune.demoHibernate.QueryTester.main(QueryTester.java:23)


The question is query.list() is returning the list of objects of pojo class. Then why is this Exception. I am new to Hibernate, sorry if its a silly question.

Answer
String hql = "select c.mobile, c.password FROM CrbtSubMasterDemo c where rownum<20";
Query query = session.createQuery(hql);

Result of this will be List<Object[]>

List<Object[]> itr = query.list();

for (Object[] row : itr) {
  System.out.println(String.format("mobile:%s, password:%s", row[0], row[1]));
}

if mobile and password are strings, of course. You can use a transformer to transform results directly to CrbtSubMasterDemo.

Hibernate 3.2: Transformers for HQL and SQL