【问题标题】:Retrieving the first item from the list and converting it in int从列表中检索第一项并将其转换为 int
【发布时间】:2016-05-09 10:47:55
【问题描述】:

我有如下的类,如下图

public class BrokerInvoiceLineItem {


    private int attachmentCount;

public int getAttachmentCount() {
        return attachmentCount;
    }

    public void setAttachmentCount(int attachmentCount) {
        this.attachmentCount = attachmentCount;
    }
}

xml中的命名查询是

<sql-query name="attachmentQuery">
     <![CDATA[select count(iilnmp.INV_LINE_NOTE_ID) from IOA_INV_LINE_NOTE_MAP iilnmp , 
                                                IOA_INVOICE_LINE_NOTES iiln , IOA_INVOICE_LINE iil
                                               where   iilnmp.INV_LINE_NOTE_ID = iiln.ID and iiln.INLI_ID =iil.id and iil.ID = ?]]>
</sql-query>

现在下面是我正在执行的操作,我从索引 0 处的列表中检索值,但我收到编译错误,因为我需要将存储在索引 0 处的值转换为 int 类型,然后只有我会能够设置 请告知我怎样才能达到同样的效果

Query query = session.getNamedQuery("attachmentQuery");
                query.setParameter(0, itrBrokerInvoiceLineItem.getId());
                List attachCount = query.list();
                if (attachCount != null && attachCount.size() > 0) {
                    if (attachCount.get(0) != null) {
                        itrBrokerInvoiceLineItem.setAttachmentCount(attachCount.get(0));
                    }
                }

我得到的编译错误是The method setAttachmentCount(int) in the type BrokerInvoiceLineItem is not applicable for the arguments (Object)

我已经编辑了我的问题,因为我使用的是休眠 3.1,其中没有 query.getsingleresult 方法,请告知

【问题讨论】:

  • 错误到底在哪里?什么是堆栈跟踪?
  • 命名查询长什么样?
  • 您已经创建了一个原始类型的List(类型Object),并且您尝试将一个值存储在int 类型中。这是不允许的。我不知道 Query.list() 返回什么值,但尝试使用菱形运算符 (List&lt;Integer&gt;) 声明您的列表。

标签: java hibernate


【解决方案1】:

替换

List attachCount = query.list();

有了这个

List<Integer> attachCount = (List<Integer>) query.list();

【讨论】:

  • 您不能在菱形运算符中使用基本类型。相反,请使用 Integer 类型。
  • 你错了
【解决方案2】:

如果我理解您的问题,您希望在执行查询后获得第一个结果。 所以,我更喜欢你使用query.getSingleResult() 处理异常而不是query.list()。这将返回Object。


(编辑后) 似乎您希望根据某些参数进行计数。 所以我希望你用这个来改变名字查询

<sql-query name="attachmentQuery">
     <![CDATA[select * from IOA_INV_LINE_NOTE_MAP iilnmp , 
                                                IOA_INVOICE_LINE_NOTES iiln , IOA_INVOICE_LINE iil
                                               where   iilnmp.INV_LINE_NOTE_ID = iiln.ID and iiln.INLI_ID =iil.id and iil.ID = ?]]>
</sql-query>

然后使用query.list().getSize() 将返回int

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    相关资源
    最近更新 更多