Convert query return to Integer

Asked

Viewed 80 times

0

How can I cast a query for Integer? Follow what I tried to execute.

public Integer validaPrincipal(String usuario, Integer tipo) {

    try{
         return (Integer) session.getCurrentSession().createNativeQuery("select count(*) from tb_sega_vip_sec where ID_VIP = '"+usuario+"' and TIPO = '"+tipo+"'").getSingleResult();
    }catch(Exception e) {
        throw new RuntimeException(e);
    }

}

and the error made:

Java.lang.RuntimeException: java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Integer
  • You don’t have to cast BigDecimal for Integer, you need to convert it to int first with the appropriate method, in case intValue().

  • So in case I will have to get back to my query and treat it with intValue()?

1 answer

2


The error message says it all: one has been returned java.math.BigDecimal, which is incompatible with java.lang.Integer, so it is not possible to do the cast from one to the other (it would only be possible if one were subclass of the other).

The solution is to first take the BigDecimal and then use the method intValue(), that returns an integer. Remembering that intValue() returns a int, then will be made a autoboxing for Integer.

Another detail is that when concatenating id and direct type values in the query, your application is vulnerable to SQL Injection. Prefer to use setParameter that avoids this kind of problem:

Query query = session.getCurrentSession()
    .createNativeQuery("select count(*) from tb_sega_vip_sec where ID_VIP = :id and TIPO = :tipo");
query.setParameter("id", usuario);
query.setParameter("tipo", tipo);
return ((BigDecimal) query.getSingleResult()).intValue();
  • Oops, thanks for the Addendum. I will test the solution and change the type of concatenation.

Browser other questions tagged

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