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?
I know this is older but 2 points to note as of today in Matt Quails Answer.
Point 1
This
Should be this
Point 2
From this
to this
would reduce other warnings obviously in original reply tag markers were stripped by the browser.
Try this:
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.
Joe Dean's solution looks interesting, but do you think it's worth it - create a new List and loop through all elements just to get rid of warnings?
(sorry, can't add a comment directly to his solution for some reason)
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 iscreateQuery(String, Class<T>)
which returnsTypedQuery<T>
. You can useTypedQuery
just as you did it withQuery
with that small difference that all operations are type safe now.So, just change your code to smth like this:
And you are all set.
Try to use
TypedQuery
instead ofQuery
. For example instead of this:-Use this:-