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

后端 未结 3 1610
我寻月下人不归
我寻月下人不归 2020-12-21 13:07

I\'m running the following query. It displays an error message. How to solve this error?

        ListrouteList=null;
        List compa         


        
相关标签:
3条回答
  • 2020-12-21 13:40

    You can just write:

    vgDetails = new Route();                                 
    vgDetails.setRouteName ((String)companyList.get(i));
    

    companyList is already a list of strings because you select just one column.

    Additionally, as Thilo's answer also suggests, you can cast your result directly to a List<string> instead of using List<?>.

    0 讨论(0)
  • 2020-12-21 13:52

    Your companyList contains Strings, not Object[].

    You should write

    List<String> companyList = (List<String>) session.createSQLQuery (
          "select name from company where company_id=?", companyId).list();
    
    
    for (String routeName: companyList) {
            vgDetails = new Route();                            
            vgDetails.setRouteName (routeName);                     
            routeList.add(vgDetails);       
        }               
    
    0 讨论(0)
  • 2020-12-21 13:53

    Hibernate is return an array of String (aka a List of type String)

     List<?> companyList = session.createSQLQuery ("select name " +
                                                      "from company "+
                                                      "where company_id= " + companyId).list();   
    

    Because your query returns a String of names from Company table.

    What you have to do return a List

     List<String> companyList = (List<String>)session.createSQLQuery ("select name " +
                                                      "from company "+
                                                      "where company_id= " + companyId).list();
    

    Change your error, from this:

     vgDetails = new Route(); 
                Object[] row = (Object[])companyList.get(i);                                 
                vgDetails.setRouteName ((String)row[0]);                     
                routeList.add(vgDetails);
    

    To this:

    vgDetails = new Route();                                
    vgDetails.setRouteName (companyList.get(i));                     
    routeList.add(vgDetails);
    

    as companyList.get(i) returns a String.

    0 讨论(0)
提交回复
热议问题