1

I'm trying to display the names of the hotels using Hibernate. But when I'm iterating the list of hotels which I have got from the database, iter.next() gives a ClassCastException saying Object cannot be cast to Hotel class. This is my method.

public List<Hotel> getAllHotels()
{
    List<Hotel> contracts = new ArrayList<Hotel>(  );
    Transaction tx = null;
    Session session = SessionFactoryUtil.getCurrentSession();
    try
    {
        tx = session.beginTransaction();
        contracts = session.createSQLQuery("select * from HOTEL").list();
        System.out.println("*** Content of the Hotel Table ***");
        System.out.println("*** Start ***");
        for ( Iterator<Hotel> iter = contracts.iterator(); iter.hasNext();) {
            Hotel h =  iter.next();
            System.out.println(h.getHotelName());
        }
        System.out.println("*** End ***");
        tx.commit();
    }
    catch( RuntimeException e )
    {
        if( tx != null && tx.isActive() )
        {
            try
            {// Second try catch as the rollback could fail as well
                tx.rollback();
            }
            catch( HibernateException e1 )
            {
                System.out.println( "Error rolling back transaction" );
            }
            // throw again the first exception
            throw e;
        }
    }
    return contracts;
}

I have used Generics for the List and Iterator but cannot figure out the error. Any help is appreciated.

2
  • 1
    Looks like the objects have a different class? And you probably want to add your exception stack trace Commented Apr 20, 2017 at 3:54
  • Different class means? Commented Apr 20, 2017 at 3:56

1 Answer 1

2

Looks like you may need to add the entity when creating the SQLQuery.

Refer https://www.mkyong.com/hibernate/hibernate-native-sql-queries-examples/

session.createSQLQuery("select * from HOTEL").addEntity(Hotel.class).list();

Or if using your current code, iterate through the object array

List result = query.list();
for(Object object : data)
         {
             //Logic 
         }
Sign up to request clarification or add additional context in comments.

2 Comments

Calling addEntity() solved the problem. Thank you very much :)
Glad that helped!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.