dcompiled
dcompiled

Reputation: 4832

Avoiding Type Safety Warnings Using Hibernate Query.list()

Is it possible to avoid cast 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 expected to find a method that specified the target object via generic parameter or method parameter such as the following:

List<User> user = session.createQuery("select u from User u").list(User.class);

Upvotes: 4

Views: 4898

Answers (3)

App Work
App Work

Reputation: 22029

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;
    }


    }

Upvotes: 0

jayunit100
jayunit100

Reputation: 17648

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?

Upvotes: 4

Finbarr
Finbarr

Reputation: 32126

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...

Upvotes: 1

Related Questions