JPA - 在IN运算符中使用长数组会引发强制转换异常 [英] JPA - using long array in IN operator throws cast exception

查看:85
本文介绍了JPA - 在IN运算符中使用长数组会引发强制转换异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于JPA来说我是新手,并且能够快速获得它,我一直试图在查询中使用IN运算符进行选择查询,并且一直在获取错误。我所做的是,我从一个函数中获取(长)消息ID数组,并使用它来根据这些ID选择记录。这里是我的查询

 从MessageTable中选择t其中t.messageId IN(:id)
query.setParameter id,id);

我刚才给你看了部分代码,实体messageId很长,在Oracle DB中它的编号。当我尝试尽可能长的变量时,它似乎不工作,当我传递长阵列。如果有人遇到这样的问题,有人可以帮忙。这是错误


14:24:49,428信息[LongType]无法将值[J @ 14f76da'绑定到
参数:1; [J不能转换为java.lang.Long



解决方案

数组 Long [] 和 long [] 不是IN的有效参数类型 -


  • Long

  • long

  • List< Long> ul>

    如果您想坚持使用JPA,而不是使用 org.Hibernate.Query.setParameterList 由Kshitij建议,您必须将您的参数转换为 List< Long>



    转换很容易完成,可以通过滚动自己或例如借助 ArrayUtil

      long [] id = {1L,2L}; 
    Long [] longs = ArrayUtils.toObject(id);
    列表< Long> list = Arrays.asList(longs);


    am new to JPA and am able to get it quickly, I had been trying a select query using "IN" operator in the query and had been getting the error as down. What I do is, i get a array of (long) message ids from a function and i use it to select the record based on those ids. Here is my query

    select t from MessageTable t where t.messageId IN (:id)  
    query.setParameter("id", id);
    

    I had just shown you part of the code, in entity messageId is long and in Oracle DB its number. When i try as just as long variable it works, it doesn't seem to work when i pass long array. Had any one come across such a problem can some one help out. This is the error

    14:24:49,428 INFO [LongType] could not bind value '[J@14f76da' to parameter: 1; [J cannot be cast to java.lang.Long

    解决方案

    Arrays Long[] and long[] are not valid types of arguments for IN when you want to check against long/Long - only following are:

    • Long
    • long and
    • List<Long>

    If you want to stick with JPA and not use org.Hibernate.Query.setParameterList suggested by Kshitij, you have to convert your argument to List<Long>.

    Conversion is easily done, either by rolling your own or for example with help of ArrayUtil:

    long[] id = {1L, 2L};
    Long[] longs = ArrayUtils.toObject(id);
    List<Long> list = Arrays.asList(longs);
    

    这篇关于JPA - 在IN运算符中使用长数组会引发强制转换异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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