0

Here is my code given below I'm not able to fetch records from my Transaction table as it displays error--java.lang.ClassCastException Ljava.lang.Object cannot be cast to com.infotech.model.Transaction

Help me out where is the issue Note- Transaction is my class

 ArrayList<Transaction> arr1 = null;
    Transaction tt1=null;

    try{

            SessionFactory sessionfactory = new Configuration().configure().buildSessionFactory();
            Session session = sessionfactory.openSession();
            session= sessionfactory.openSession();
            session.beginTransaction();
    int uid = search.getUser_id();
    Query query1=session.createQuery("select A_no, date, type, B_id from Transaction t where t.user_id=:uid");
            query1.setInteger("uid", uid);



            List<Transaction> list=query1.list();

             Iterator<Transaction> itr1=list.iterator();
                arr1=new ArrayList<Transaction>();


                while(itr1.hasNext())
                {
                     tt1=itr1.next();
                     arr1.add(tt1);
                    System.out.println(tt1.getA_no()+"\t"+tt1.getB_id());
                }

           }catch(Exception ex){ex.printStackTrace();} 


            ModelAndView m=new ModelAndView("form-search","data",tt);
            m.addObject("copy", arr1);
rajat kumar
  • 35
  • 1
  • 10
  • try this query1.setResultTransformer(Transformers.aliasToBean(Transaction.class)).list(); instead of this query1.list(). – Ajay Garg Dec 18 '17 at 10:03

2 Answers2

1

The problem here is that when you use projections Hibernate returns List<Object[]> (not List<Transaction>).

The simplest thing is to change the HQL query, just to check that everything works

Query query1 = session.createQuery("from Transaction t where t.user_id=:uid");

Please, read this if you want to use projections

SpringBoot+Hibernate+Restful : format response

v.ladynev
  • 19,275
  • 8
  • 46
  • 67
0

It must be this line:

List<Transaction> list=query1.list();

You should change it to List<Transaction> list= (List<Transaction>)(List<?>) query1.list();

Java requires explicit type casting from derived types to base types.

JustBaron
  • 2,319
  • 7
  • 25
  • 37