简体   繁体   中英

how to cast the result to String From Native Query in Java?

i have a query which will return single record with 2 columns from Table i want to get the result to a List each element hold a column value , but i keep getting ClassCastExceptoion this is the code :

public List<String> getStatus(Long requestId) {
    List result = new ArrayList();
    if (requestId != null)

    {
        StringBuilder querySBuilder = new StringBuilder();
        querySBuilder.append(" select R.request_status_id , L.request_status_desc ");
        querySBuilder.append(" from Table1 R join  Table2 L ");
        querySBuilder.append(" on R.request_status_id = L.REQUEST_STATUS_Id ");
        querySBuilder.append(" where R.REQUEST_ID =  " + requestId);
        System.out.print(querySBuilder.toString());
        List resultList =
           em.createNativeQuery(querySBuilder.toString()).getResultList();
        Vector resultVec = (Vector)resultList.get(0);

        int id = ((BigDecimal)resultVec.elementAt(0)).intValue();
        String statusName = ((String)resultVec.elementAt(0));

        System.out.println("id" + id);
        System.out.println("name " + statusName);
        result.add(id);
        result.add(statusName);
        if (resultVec == null || resultVec.isEmpty()) {
            return new ArrayList<String>();
        }
        return result;


    }

    return null;
}

The pattern I would use would be to phrase the incoming native result set as a List<Object[]> , where each object array represents a single record:

Query q = em.createNativeQuery(querySBuilder.toString());
List<Object[]> result = q.getResultList();

for (Object[] row : result) {
    int id = (Integer)row[0];
    String statusName = (String)row[1];

    // do something with the id and statusName from above
}

I think it is a typo.

String statusName = ((String)resultVec.elementAt(0));

The elementAt(1) should be used instead of elementAt(0).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM