How to avoid type safety warnings with Hibernate HQL results?
JavaGenericsJava Problem Overview
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 shows the following warning
Type safety: The expression of type List needs unchecked conversion to conform to List<Cat>
List<Cat> cats = q.list();
Is there a way to avoid it?
Java Solutions
Solution 1 - Java
Using @SuppressWarnings
everywhere, as suggested, is a good way to do it, though it does involve a bit of finger typing each time you call q.list()
.
There are two other techniques I'd suggest:
Write a cast-helper
Simply refactor all your @SuppressWarnings
into one place:
List<Cat> cats = MyHibernateUtils.listAndCast(q);
...
public static <T> List<T> listAndCast(Query q) {
@SuppressWarnings("unchecked")
List list = q.list();
return list;
}
Prevent Eclipse from generating warnings for unavoidable problems
In Eclipse, go to Window>Preferences>Java>Compiler>Errors/Warnings and under Generic type, select the checkbox
Ignore unavoidable generic type problems due to raw APIs
This will turn off unnecessary warnings for similar problems like the one described above which are unavoidable.
Some comments:
- I chose to pass in the
Query
instead of the result ofq.list()
because that way this "cheating" method can only be used to cheat with Hibernate, and not for cheating anyList
in general. - You could add similar methods for
.iterate()
etc.
Solution 2 - Java
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.
Solution 3 - Java
We use @SuppressWarnings("unchecked")
as well, but we most often try to use it only on the declaration of the variable, not on the method as a whole:
public List<Cat> findAll() {
Query q = sess.createQuery("from Cat cat");
@SuppressWarnings("unchecked")
List<Cat> cats = q.list();
return cats;
}
Solution 4 - Java
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();
Solution 5 - Java
In our code we annotate the calling methods with:
@SuppressWarnings("unchecked")
I know it seems like a hack, but a co-developer checked recently and found that was all we could do.
Solution 6 - Java
Apparently, the Query.list() method in the Hibernate API is not type safe "by design", and there are no plans to change it.
I believe the simplest solution to avoid compiler warnings is indeed to add @SuppressWarnings("unchecked"). This annotation can be placed at the method level or, if inside a method, right before a variable declaration.
In case you have a method that encapsulates Query.list() and returns List (or Collection), you also get a warning. But this one is suppressed using @SuppressWarnings("rawtypes").
The listAndCast(Query) method proposed by Matt Quail is less flexible than Query.list(). While I can do:
Query q = sess.createQuery("from Cat cat");
ArrayList cats = q.list();
If I try the code below:
Query q = sess.createQuery("from Cat cat");
ArrayList<Cat> cats = MyHibernateUtils.listAndCast(q);
I'll get a compile error: Type mismatch: cannot convert from List
Solution 7 - Java
It's not an oversight or a mistake. The warning reflects a real underlying problem - there is no way that the java compiler can really be sure that the hibernate class is going to do it's job properly and that the list it returns will only contain Cats. Any of the suggestions here is fine.
Solution 8 - Java
No, but you can isolate it into specific query methods and suppress the warnings with a @SuppressWarnings("unchecked")
annotation.
Solution 9 - Java
Newer versions of Hibernate now support a type safe Query<T>
object so you no longer have to use @SuppressWarnings
or implement some hack to make the compiler warnings go away. In the Session API, Session.createQuery
will now return a type safe Query<T>
object. You can use it this way:
Query<Cat> query = session.createQuery("FROM Cat", Cat.class);
List<Cat> cats = query.list();
You can also use it when the query result won't return a Cat:
public Integer count() {
Query<Integer> query = sessionFactory.getCurrentSession().createQuery("SELECT COUNT(id) FROM Cat", Integer.class);
return query.getSingleResult();
}
Or when doing a partial select:
public List<Object[]> String getName() {
Query<Object[]> query = sessionFactory.getCurrentSession().createQuery("SELECT id, name FROM Cat", Object[].class);
return query.list();
}
Solution 10 - Java
We had same problem. But it wasn't a big deal for us because we had to solve other more major issues with Hibernate Query and Session.
Specifically:
- control when a transaction could be committed. (we wanted to count how many times a tx was "started" and only commit when the tx was "ended" the same number of times it was started. Useful for code that doesn't know if it needs to start a transaction. Now any code that needs a tx just "starts" one and ends it when done.)
- Performance metrics gathering.
- Delaying starting the transaction until it is known that something will actually be done.
- More gentle behavior for query.uniqueResult()
So for us, we have:
- Create an interface (AmplafiQuery) that extends Query
- Create a class (AmplafiQueryImpl) that extends AmplafiQuery and wraps a org.hibernate.Query
- Create a Txmanager that returns a Tx.
- Tx has the various createQuery methods and returns AmplafiQueryImpl
And lastly,
AmplafiQuery has a "asList()" that is a generic enabled version of Query.list() AmplafiQuery has a "unique()" that is a generic enabled version of Query.uniqueResult() ( and just logs an issue rather than throwing an exception)
This is a lot of work for just avoiding @SuppressWarnings. However, like I said (and listed) there are lots of other better! reasons to do the wrapping work.
Solution 11 - Java
I know this is older but 2 points to note as of today in Matt Quails Answer.
Point 1
This
List<Cat> cats = Collections.checkedList(Cat.class, q.list());
Should be this
List<Cat> cats = Collections.checkedList(q.list(), Cat.class);
Point 2
From this
List list = q.list();
to this
List<T> list = q.list();
would reduce other warnings obviously in original reply tag markers were stripped by the browser.
Solution 12 - Java
Try this:
Query q = sess.createQuery("from Cat cat");
List<?> results = q.list();
for (Object obj : results) {
Cat cat = (Cat) obj;
}
Solution 13 - Java
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);
Solution 14 - Java
TypedQuery<EntityName> createQuery = entityManager.createQuery("from EntityName", EntityName.class);
List<EntityName> resultList = createQuery.getResultList();
Solution 15 - Java
If you don't want to use @SuppressWarnings("unchecked") you can do the following.
Query q = sess.createQuery("from Cat cat");
List<?> results =(List<?>) q.list();
List<Cat> cats = new ArrayList<Cat>();
for(Object result:results) {
Cat cat = (Cat) result;
cats.add(cat);
}
FYI - I created a util method that does this for me so it doesn't litter my code and I don't have to use @SupressWarning.