Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve java.lang.ClassCastException: for query.list() in hibernate

Tags:

java

hibernate

I am performing select option using Hibernate, Query is executing but getting exception at query.list() method,

Here is my code,

String hql="select a.vehicleno, a.lat, a.lng, a.status, a.rdate, a.rtime from LatitudeBean a, VehicleRegisterBean b where a.vehicleno=b.vehicleno and b.clientid= :clientId and b.groupid in(select groupid from GroupDetails where groupname= :groupname and clientid= :gdclientId)"; // valid query
Query query =sessio.createQuery(hql);
List<LatitudeBean> groupList = (List<LatitudeBean>)query.list(); //Here I am getting exception
for(LatitudeBean arr : groupList){
        System.out.println(arr.getVehicleno());
    }

Exception is,

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.aurodisplay.its.beans.LatitudeBean
at com.abc.its.controller.LoginController.doPost(LoginController.java:83)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)

How to cast list returning from list() method . Anyone help me in this please.

like image 639
Raghu Avatar asked Feb 13 '23 04:02

Raghu


1 Answers

The problem is that your query does not select entities, but just properties of entities.

Therefore the result will not be a list of entities, but a list of object arrays (which arrays will hold the selected properties).

Try this:

List<Object[]> groupList = (List<Object[]>) query.list();
for(Object[] arr : groupList) {
    System.out.println("vehicleno: " + arr[0]);
}

Or if you want to select entire entities, modify your query like this:

String hql = "select a from LatitudeBean a, VehicleRegisterBean b where ...";

And that way your original code will work.

like image 95
icza Avatar answered Feb 15 '23 10:02

icza