0

I'm still a newbie at Hibernate and am trying to retrieve the results from a simple SELECT query. I keep getting a ClassCastException however. Can anyone tell me what I'm doing wrong here?

Here's the code:

public Wo getWoById(int id) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();
    List<Wo> result = (List<Wo>) session.createQuery("from Wo where woid = " + id);

    if (result!=null && result.size()==1) 
        return result.get(0); 
    else return null;
}

...and the error message:

Exception in thread "main" java.lang.ClassCastException:   
org.hibernate.internal.QueryImpl cannot be cast to java.util.List
at implDAO.WoImplDAO.getWoById(WoImplDAO.java:16)
at logic.Logic.deleteWo(Logic.java:72)
at nl.hanze.funda.admin.main.Main.<init>(Main.java:20)
at nl.hanze.funda.admin.main.Runner.main(Runner.java:16)
Anubis
  • 1,162
  • 4
  • 14
  • 31

2 Answers2

0

session.createQuery() returns a Query. It doesn't return the list of its results. You forgot to execute the query:

List<Wo> result = (List<Wo>) session.createQuery("from Wo where woid = " + id)
                                    .list();

Also, you should use parameters instead of String concatenation:

List<Wo> result = (List<Wo>) session.createQuery("from Wo where woid = :id")
                                    .setParameter("id", id)
                                    .list();

Or, even simpler (and more efficient) since you're querying by ID:

return ((Wo) session.get(Wo.class, id));
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

Please change the query to

List<Wo> result = (List<Wo>) session.createQuery("from Wo where woid = " + id).list() 
Srivatsa N
  • 2,291
  • 4
  • 21
  • 36