如何通过Hibernate HQL结果避免类型安全警告? [英] How to avoid type safety warnings with Hibernate HQL results?

查看:237
本文介绍了如何通过Hibernate HQL结果避免类型安全警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有这样的查询:

$ p $ Query q = sess.createQuery(from cat cat);
列表cats = q.list();

如果我试图做这样的事情,它会显示警告类型安全:类型列表需要进行未经检查的转换以符合列表:

 列表< Cat> cats = q.list(); 

有没有办法避免它?

解决方案

使用 @SuppressWarnings 无处不在,就像建议的那样,这是一个很好的方法,尽管它确实需要一些手指输入每次你调用 q.list()



还有其他三种技巧我会建议: p>

Collections.checkedList()

使用此替换您的任务:

 列表< Cat> cats = Collections.checkedList(q.list(),Cat.class); 

您可能需要检查该方法的javadoc ,特别是关于等于 hashCode



编写一个转换助手



只需将所有 @SuppressWarnings 重构为一个地方即可:

 列表与LT;目录> cats = MyHibernateUtils.listAndCast(q); 

...

public static< T>列表与LT; T> listAndCast(Query q){
@SuppressWarnings(unchecked)
List list = q.list();
返回列表;

防止Eclipse针对不可避免的问题产生警告 <在Eclipse中,转到Window> Preferences> Java> Compiler> Errors / Warnings,然后在Generic type下,选中复选框
忽略不可避免的由原始API引起的泛型类型问题



这将关闭类似问题的不必要的警告,如上面所述,这是不可避免的。 >

一些评论:


  • 我选择传入 Query 而不是 q.list()的结果,因为这种欺骗方法只能用于作弊,而不能用于欺骗任何 List 一般。

  • 您可以为 .iterate()等。


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?

解决方案

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 three other techniques I'd suggest:

Collections.checkedList()

Replace your assignment with this:

List<Cat> cats = Collections.checkedList(q.list(), Cat.class);

You might want to check the javadoc for that method, especially with regards to equals and hashCode.

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.

这篇关于如何通过Hibernate HQL结果避免类型安全警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆