Error picking value returned with query.getResultList(). get(0)

Asked

Viewed 71 times

1

I need to get the value of a query, simply a field and I’m making the following mistake:

java.math.BigDecimal cannot be cast to java.lang.String.

My DAO is like this:

public String buscaCodColaborador() throws MetrusDAOException{
    EntityManager em = null;
    try {
        StringBuilder sqlString = new StringBuilder();
        sqlString
            .append(" SELECT LEVEL FROM DUAL CONNECT BY LEVEL <= 9999 ")
            .append(" MINUS")
            .append(" SELECT COD_COLABORADOR FROM ME_COLABORADORES");

        em = getEntityManager();

        Query query = em.createNativeQuery(sqlString.toString());

        String codColaboradorDisponivel = (String) query.getResultList().get(0);

        return codColaboradorDisponivel;
    } catch (Exception e) {
        logger.error(e, e);
        throw new MetrusDAOException(e);
    } finally {
        closeEntityManager(em);
    }
}

I just need to take a bank value and later set in my Business the value returned in a field Long. I’ve tried using the FindFirst stream but I’m always taking these conversion errors.

  • 1

    There’s a big decimal in that get(0) there this error is happening at the time of conversion, instead of giving the cast to the string just give a get(0). toString()...

  • Thank you @Lucasmiranda this solution solved my problem.

1 answer

1


A cast is only possible when the types involved are compatible with each other, that is, when one is a subtype of another. For example:

class Animal { etc... }
class Gato extends Animal {
    // só gato fazem miau
    public void miau() { etc... }
}

Animal a = new Gato();
a.miau(); // erro: classe Animal não tem o método miau

// assim funciona
Gato g = (Gato) a; // fazendo cast para outro tipo compatível
g.miau(); // agora funciona
// ou ainda
((Gato) a).miau();

When the classes have no hierarchy relation to each other (one is not subclass of the other), the cast is not possible. This is the case of String and BigDecimal, hence the error "java.math.Bigdecimal cannot be cast to java.lang.String".

If you want to convert to String, one way to do it is simply to call toString:

String codColaboradorDisponivel = query.getResultList().get(0).toString();

But if that value is a number, wouldn’t the method be better buscaCodColaborador() return a BigDecimal (or any other numerical type)? You yourself said that you then need to take "the value returned in a Long field", then to which convert to String? Make the method already return the type you need. For example, if you want it to be a long:

public long buscaCodColaborador() throws MetrusDAOException {
    ...
    BigDecimal codColaboradorDisponivel = (BigDecimal) query.getResultList().get(0);
    return codColaboradorDisponivel.longValue();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.