What is the “proper” way to cast Hibernate Query.list() to List?

后端 未结 10 1657
梦谈多话
梦谈多话 2020-12-04 11:44

I\'m a newbie with Hibernate, and I\'m writing a simple method to return a list of objects matching a specific filter. List seemed a natural return t

10条回答
  •  自闭症患者
    2020-12-04 12:41

    Short answer @SuppressWarnings is the right way to go.

    Long answer, Hibernate returns a raw List from the Query.list method, see here. This is not a bug with Hibernate or something the can be solved, the type returned by the query is not known at compile time.

    Therefore when you write

    final List list = query.list();
    

    You are doing an unsafe cast from List to List - this cannot be avoided.

    There is no way you can safely carry out the cast as the List could contain anything.

    The only way to make the error go away is the even more ugly

    final List list = new LinkedList<>();
    for(final Object o : query.list()) {
        list.add((MyObject)o);
    }
    

提交回复
热议问题