fen1ksss
fen1ksss

Reputation: 1120

Cann't retrieve item from DB hql

Having this code:

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("from DBUser where id=1");
    for(Iterator it=query.iterate();it.hasNext();){
    Object[] row = (Object[]) it.next();
    System.out.println("ID: " + row[0]);
    System.out.println("Name: " + row[1]);
    System.out.println("Amount: " + row[2]);
}

An error occur: java.lang.ClassCastException: com.mycompany.app.DBUser cannot be cast to [Ljava.lang.Object;

Probably there is more simple way to retrieve a single element from the table?

Upvotes: 0

Views: 36

Answers (1)

rbernabe
rbernabe

Reputation: 1072

hql returns the mapped type in this case. Your code should look like:

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("from DBUser where id=1");
    for(Iterator it=query.iterate();it.hasNext();){
    DBUser row = (DBUser) it.next();
    System.out.println("ID: " + row.getId());
    System.out.println("Name: " + row.getName());
    System.out.println("Amount: " + row.getAmount());
}

Upvotes: 2

Related Questions