简体   繁体   English

返回空列表的javax.persistence.Query.getResultList()

[英]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. 我看到 ,知道现在正在返回清单。

  • Since which version this change has come to effect? 从哪个版本开始,此更改生效?
  • How the hibernate decide the size of this list? 休眠状态如何决定此列表的大小?
  • How to stay away from this kind of errors in general? 一般如何避免此类错误?

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返回一个没有显式capacityArrayList 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()返回truelist.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
  • At least version 3.2.7 至少版本3.2.7
  • To avoid these kind of crashes, always always verify input. 为避免此类崩溃,请务必始终验证输入。 Whether you pull it from forms, databases, files or whatever kind of source. 无论是从表单,数据库,文件还是任何类型的源中提取它。 Verify that what you receive is what you expect it to be, otherwise discard/omit it. 验证收到的内容与预期的一样,否则丢弃/忽略它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM