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.