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

后端 未结 10 1670
梦谈多话
梦谈多话 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:14

    The resolution is to use TypedQuery instead. When creating a query from the EntityManager instead call it like this:

    TypedQuery<[YourClass]> query = entityManager.createQuery("[your sql]", [YourClass].class);
    List<[YourClass]> list = query.getResultList(); //no type warning
    

    This also works the same for named queries, native named queries, etc. The corresponding methods have the same names as the ones that would return the vanilla query. Just use this instead of a Query whenever you know the return type.

提交回复
热议问题