-1

when i iterate by using the foreach loop, i get ClassCast Exception. i dont know why ?

public List<MailData> getAllMailData() {
 String strqry="select c.created_time as created_time, c.hangup_time as hangup_time, c.direction as direction ,
     c.sip_endpoint_disposition as sip_endpoint_disposition, v.cid_number as cid_number, v.in_folder as in_folder, 
     v.message_len as message_len,v.read_flags as read_flags, v.username as username from onyxcxm_db.cdr c  
     inner join onyxcxm_db.mail_msgs v on c.orig_id=v.uuid";    

 List<MailData> listMailData = (List<MailData>)getSession().createNativeQuery(strqry).list();

   for(MailData md:listMailData){
    System.out.println(md.getcreated_time);  //line 44
       }
        getSession().flush();
    return listvoiceMailData;   
}

and Error like,

SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/hello] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.my.models.MailData] with root cause java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.my.models.MailData at com.neron.daoImpl.MailDataDaoImpl.getAllMailData(MailDataDaoImpl.java:44) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) Can any one solve it ? Thanks..

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sushil Kumar
  • 84
  • 1
  • 10
  • Possible duplicate of [Hibernate SQL Query result Mapping/Convert TO Object/Class/Bean](https://stackoverflow.com/questions/17355980/hibernate-sql-query-result-mapping-convert-to-object-class-bean) – Amogh Sep 29 '18 at 08:44

2 Answers2

1

Instead of use addScalar you can do this:

List<MailData> listMailData = getSession().createSQLQuery(strqry)
.addEntity(MailData.class)
.list();
lugolu
  • 86
  • 1
  • 7
  • 2
    Wow thanks, addEntity() is also a good solution. and new addScallar() is depricated in Hibernate 5 and `.list()` is also depricated you can update it as `.getResultList()`. – Sushil Kumar Jan 03 '19 at 11:30
0

Finally i get the Solution using Query:

Query query = getSession().createSQLQuery(strqry)  
             .addScalar("created_time", new StringType())      
             .addScalar("hangup_time", new StringType())  
             .addScalar("direction", new StringType())      
             .addScalar("sip_endpoint_disposition", new StringType())  
             .addScalar("cid_number", new StringType())      
             .addScalar("in_folder", new StringType())  
             .addScalar("read_flags", new StringType())      
             .addScalar("username", new StringType())  
             .addScalar("username", new StringType())  
             .setResultTransformer(Transformers.aliasToBean(MailData.class));

     List<MailData> listMailData = query.getResultList();
Khalid Shah
  • 3,132
  • 3
  • 20
  • 39
Sushil Kumar
  • 84
  • 1
  • 10