避免类型安全警告使用Hibernate Query.list() [英] Avoiding Type Safety Warnings Using Hibernate Query.list()

查看:498
本文介绍了避免类型安全警告使用Hibernate Query.list()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用createQuery()。list?之后,是否可以避免强制转换警告?

  //类型安全:类型List需要未检查的转换以符合List< User> 
List< User> user =(List< User>)session.createQuery(select u from User u)list();

我希望找到一个通过通用参数或方法参数指定目标对象的方法, :

 列表< User> user = session.createQuery(select u from User u)。list(User.class); 


解决方案

要记住的最重要的事情是警告是由于您的编译器,而不是hibernate - 您可以告诉您的编译器忽略未实现的泛型。通过使用HQL,我们以类型安全的方式查询数据,不幸的是,java不能验证。



有很多如果得到的方法围绕hibernate转换的语法丑陋,像:



1)使用@suppressWarnings在其中转换或



<请使用Collections.checkedList方法创建新列表。



另请参阅:


Is it possible to avoid cast warnings after using createQuery().list?

//Type safety: The expression of type List needs unchecked conversion to conform to List<User>
List<User> user = (List<User>) session.createQuery("select u from User u").list();

I expected to find a method that specified the target object via generic parameter or method parameter such as the following:

List<User> user = session.createQuery("select u from User u").list(User.class);

解决方案

The most important thing to remember is that warnings are due to your compiler, not hibernate - you can tell your compiler to ignore unimplemented generics. By using HQL, we are querying for data in a type safe way that, unfortunately, java does not have the ability to verify.

There are a lot if ways to get around the syntactical ugliness of hibernate casting , like :

1) use @suppressWarnings where casting or

2) use the Collections.checkedList method to create the new list.

See also : How to avoid type safety warnings with Hibernate HQL results?

这篇关于避免类型安全警告使用Hibernate Query.list()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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