How to avoid type safety warnings with Hibernate H

2019-01-03 04:27发布

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?

16条回答
SAY GOODBYE
2楼-- · 2019-01-03 05:03

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.

查看更多
Anthone
3楼-- · 2019-01-03 05:06

Try this:

Query q = sess.createQuery("from Cat cat");
List<?> results = q.list();
for (Object obj : results) {
    Cat cat = (Cat) obj;
}
查看更多
迷人小祖宗
4楼-- · 2019-01-03 05:07

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.

查看更多
相关推荐>>
5楼-- · 2019-01-03 05:10

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)

查看更多
淡お忘
6楼-- · 2019-01-03 05:14

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.

查看更多
Evening l夕情丶
7楼-- · 2019-01-03 05:14

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();
查看更多
登录 后发表回答