Is it possible to avoid cast warnings after using createQuery().list?
//Type safety: The expression of type List needs unchecked conversion to conform to Lis
You can avoid the warnings if you use an EntityManager, but not sure if it makes things any 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: obviously, there are nicer ways of setting this out...
The most important thing to remember is that warnings are due to your compiler, not hibernate - you can tell your compiler to ignore unimplemented generics. By using HQL, we are querying for data in a type safe way that, unfortunately, java does not have the ability to verify.
There are a lot of ways to get around the syntactical ugliness of hibernate casting , like :
1) use @suppressWarnings where casting or
2) use the Collections.checkedList method to create the new list.
See also : How to avoid type safety warnings with Hibernate HQL results?
Since JPA 2.0 , EntityManager has added following overloaded createQuery()/createNamedQuery() methods that return TypedQuery to solve the propblem:
TypedQuery<T> entityManager.createQuery(CriteriaQuery<T> criteriaQuery)
TypedQuery<T> entityManager.createQuery(java.lang.String qlString, java.lang.Class<T> resultClass)
TypedQuery<T> entityManager.createNamedQuery(java.lang.String name, java.lang.Class<T> resultClass)
Example:
@Repository
public class UsersRepositoryImpl implements IUsersRepository {
@PersistenceContext(unitName="SPRING_BOOT_JPA_DS_PU")
private EntityManager entityManager;
@Override
public List<User> listUser() {
String queryString = "SELECT U FROM " + User.class.getName() + " U";
// Query query =entityManager.createQuery(queryString);
// Use TypedQuery instead of Query
// Requires JPA 2.0
TypedQuery<User> query = entityManager.createQuery(queryString, User.class);
List<User> resultList = query.getResultList();
return resultList;
}
}