JPA - using long array in IN operator throws cast exception

匆匆过客 提交于 2020-01-23 13:13:10

问题


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


回答1:


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
  • Collection<Long> (collection_valued_input_parameter)

If you want to stick with JPA and not use org.Hibernate.Query.setParameterList suggested by Kshitij, you have to convert your argument to Collections<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);
Collection<Long> list = Arrays.asList(longs);



回答2:


try this:

query.setParameterList("id", ids);


来源:https://stackoverflow.com/questions/10682735/jpa-using-long-array-in-in-operator-throws-cast-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!