Avoiding type safety warnings using Hibernate Query.list ()

Is it possible to avoid throw warnings after using createQuery (). list?

//Type safety: The expression of type List needs unchecked conversion to conform to List<User> List<User> user = (List<User>) session.createQuery("select u from User u").list(); 

I was expecting to find a method that defined the target through a generic parameter or method parameter, for example the following:

 List<User> user = session.createQuery("select u from User u").list(User.class); 
+4
source share
2 answers

The most important thing to remember is that warnings are due to your compiler, not hibernate - you can tell your compiler to ignore unrealized generics. Using HQL, we query the data in a safe way, which, unfortunately, java has no way to check.

There are many ways to overcome the syntactic ugliness of casting hibernation, for example:

1) use @suppressWarnings where casting or

2) use the Collections.checkedList method to create a new list.

See also: How to avoid type safety warnings with Hibernate HQL results?

+4
source

You can avoid warnings if you use EntityManager , but you are not sure that it does something nicer:

 EntityManager em = provider.get(); // your code will probably be different here CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<T> query = builder.createQuery(type); // your Class<T> Root<T> root = query.from(type); // your Class<T> query.select(root); TypedQuery<T> typedQuery = em.createQuery(query); typedQuery.getResultList(); // List<T> 

Edit: There are obviously more convenient ways to configure this ...

+1
source

Source: https://habr.com/ru/post/1388231/


All Articles