简体   繁体   English

如何将结果从Java中的本机查询转换为字符串?

[英]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 : 我有一个查询,该查询将返回表中具有2列的单个记录,我想将结果获取到列表中,每个元素都包含一个列值,但是我一直在获取ClassCastExceptoion,这是代码:

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: 我将使用的模式是将传入的本机结果集表示为List<Object[]> ,其中每个对象数组代表一个记录:

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)); 字符串statusName =((String)resultVec.elementAt(0));

The elementAt(1) should be used instead of elementAt(0). 应该使用elementAt(1)代替elementAt(0)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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