使用带有泛型的java List Iterator的ClassCastException

时间:2021-08-27 15:51:36

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.

我正在尝试使用Hibernate显示酒店的名称。但是,当我在迭代我从数据库获得的酒店列表时,iter.next()给出了一个ClassCastException,指出Object不能转换为Hotel类。这是我的方法。

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.

我已经使用Generics作为List和Iterator但是无法弄清楚错误。任何帮助表示赞赏。

1 个解决方案

#1


2  

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

看起来您可能需要在创建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 
         }

#1


2  

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

看起来您可能需要在创建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 
         }