[英]javax.persistence.Query.getResultList() returning null list
I am using getResultList ( List javax.persistence.Query.getResultList() )
in my dao to fetch a list of objects. 我在dao中使用
getResultList ( List javax.persistence.Query.getResultList() )
来获取对象列表。 Any idea why it may return {null,null,null,null,null,null,null,null,null,null}
for a query which was has no match in the db. 知道为什么它可能针对数据库中没有匹配的查询返回
{null,null,null,null,null,null,null,null,null,null}
。 This is causing my code List. 这导致我的代码列表。
hasNext()
to break which was working fine earlier. hasNext()
可以中断,它之前工作得很好。 I wasn't working in this project for a while (If it matters). 我有一段时间没有在这个项目中工作了(如果很重要)。 It's using
正在使用
hibernate-core-4.1.9.Final-sources.jar
hibernate-core-4.1.9.Final-sources.jar
I saw this and understands it is returning list now. 我看到了 ,知道现在正在返回清单。
Just guessing: You checked your list in the debugger and didn't look at the size
property? 只是猜测:您在调试器中检查了列表,没有查看
size
属性? Hibernate returns an ArrayList
without an explicit capacity
in many cases. 在许多情况下,Hibernate返回一个没有显式
capacity
的ArrayList
。 And the ArrayList
initializes its internal array with 10 null
elements then (to avoid creating an array again and again while adding elements). 然后
ArrayList
用10个null
元素初始化其内部数组(以避免在添加元素时一次又一次创建数组)。 But if you ask list.iterator().hasNext()
it should return false
(as well as list.isEmpty()
returns true
and list.size()
returns 0
). 但是,如果您询问
list.iterator().hasNext()
它应该返回false
(以及list.isEmpty()
返回true
和list.size()
返回0
)。
Just add an isEmpty
check on the result list: 只需添加一个
isEmpty
结果列表上的检查:
List<SomeType> resultList = query.getResultList();
if (resultList.isEmpty()){
//Handle it
}
The result list somehow always contains some nulls, I used the isEmpty check to prevent errors later on. 结果列表总以某种方式包含一些空值,我使用了isEmpty检查以防止以后出现错误。
You could prevent this by checking for null elements in your List.hasNext(). 您可以通过检查List.hasNext()中的空元素来防止这种情况。
if(variable = list.next() !=null)
// do something
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.