How to avoid type safety warnings with Hibernate HQL results?

By : serg
Source: Stackoverflow.com
Question!

For example I have such query:

Query q = sess.createQuery("from Cat cat");
List cats = q.list();

If I try to make something like this it will show warning "Type safety: The expression of type List needs unchecked conversion to conform to List":

List<Cat> cats = q.list();

Is there a way to avoid it?

By : serg


Answers

Try to use TypedQuery instead of Query. For example instead of this:-

Query q = sess.createQuery("from Cat cat", Cat.class);
List<Cat> cats = q.list();

Use this:-

TypedQuery<Cat> q1 = sess.createQuery("from Cat cat", Cat.class);
List<Cat> cats = q1.list();


A good solution to avoid type safety warnings with hibernate query is to use a tool like TorpedoQuery to help you to build type safe hql.

Cat cat = from(Cat.class);
org.torpedoquery.jpa.Query<Entity> select = select(cat);
List<Cat> cats = select.list(entityManager);
By : xjodoin


It is been a long time since the question was asked but I hope my answer might be helpful to someone like me.

If you take a look at javax.persistence api docs, you will see that some new methods have been added there since Java Persistence 2.0. One of them is createQuery(String, Class<T>) which returns TypedQuery<T>. You can use TypedQuery just as you did it with Query with that small difference that all operations are type safe now.

So, just change your code to smth like this:

Query q = sess.createQuery("from Cat cat", Cat.class);
List<Cat> cats = q.list();

And you are all set.

By : antonpp


This video can help you solving your question :)
By: admin