Java – How to avoid type safety warnings with Hibernate HQL results

genericsjava

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?

Best Answer

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 of q.list() because that way this "cheating" method can only be used to cheat with Hibernate, and not for cheating any List in general.
  • You could add similar methods for .iterate() etc.