NGS NGS - 13 days ago 10
Java Question

list.get().method generate cast exception

I have written a code like this to fetch data from database using HQL:

Query qr=sess.createQuery("select i.contract_Vcode,i.installment_date from Installment i where i.vcode=:instalVcode").setParameter("instalVcode", installVcode);
qr.getNamedParameters();
List<Installment> li=null;
li=qr.list();
int coVcode=li.get(0).getContract_Vcode();


As I know the
contract_Vcode
is an integer. But when I want to run it, the followed error happens:

Error invoking Action using Hibernate Core Session / Transaction injection
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to information.Installment


More over when I want to see the exact element like this,

System.out.println("contract installDate is: "+li.get(0).getContract_Vcode());


Same error happens. How can I fix this?

Answer

You're currently only querying two parts of an installment. If you want to fetch the whole thing, I'd expect something like:

Query qr = sess.createQuery(
                    "select from Installment as i where i.vcode=:instalVcode")
               .setParameter("instalVcode", installVcode);

If you fetch multiple properties (instead of whole entities), you just get back an Object[] for each row in the results.

So you could use your original query, but:

List<Object[]> li = qr.list();
int coVcode = (Integer) li.get(0)[0]; // 1st column of 1st row