简体   繁体   English

Java使用bytearray列表创建nativequery

[英]Java creating nativequery with list of bytearray

Hi i am trying to pass list of byteArray to a SQL query but my code doesn't work. 您好我正在尝试将byteArray列表byteArray给SQL查询,但我的代码不起作用。

public List<Message> findAll(List<byte[]> ids) {
    String sqlString = "SELECT * FROM MYTABLE WHERE ID in (" + StringUtils.join(ids, ',') + ")";    
    Query query = em.createNativeQuery(sqlString).setParameter(1, ids); 
    return query.getResultList();
}

Your ids is a list of byte arrays (ie, it has two dimensions). 你的id是一个字节数组列表(即它有两个维度)。 The StringUtils.join method doesn't work with that. StringUtils.join方法不适用StringUtils.join Plus you don't need to set arrays as a parameter as you haven't specified any parameters in your query. 此外,您不需要将数组设置为参数,因为您未在查询中指定任何参数。

If you output your SQL string you will see that it is not at all correct. 如果输出SQL字符串,您将看到它完全没有问题。

You will have to flatten out your list of arrays first before using it. 在使用之前,您必须先将数组列表展平。 Someone can probably do this with streams in one line of code, but an easier way is to use a for loop and a new array. 有人可以在一行代码中使用流来执行此操作,但更简单的方法是使用for循环和新数组。

I haven't tested this, but something like: 我没有测试过这个,但是类似于:

List<Strings> list = new ArrayList<>();
for (byte[] idArray : ids) {
    list.add(StringUtils.join(idArray, ','); // join each array
}
String all = StringUtils.join(list, ','); // join all of the arrays

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

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