Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How set Array/List in Spring jdbcTemplate as parameter?

I have SQL query with many placeholders '?', that builds dynamically, I want to put array of values to replace placeholders. Size of array can be different every time. Array consists from all parameters in order.

return jdbcTemplate.query(Queries.someQuery,
    new Object[] {/* Array must be here */},
    new ResultSetExtractor<List<String>>() {
        @Override
        public List<String> extractData(ResultSet resultSet) 
        }
    });

Example of sql generations:

for (int j = 0; j < y; j++) {
        conditionsBuilder.append("\n and p"+i+".object_id=o.object_id\n" +
                "    and p"+i+".attr_id =?\n" +
                "    and p"+i+".value =?\n");
        tablesBuilder.append(",patameters p"+i+" ");
        i++;
    }
like image 718
I. James Avatar asked Jan 29 '26 15:01

I. James


1 Answers

Use an ArrayList:

ArrayList<Object> values = new ArrayList<>;

In your for loop you should add the values in the order they appear in the query:

values.add(value);

Then turn it into an array:

return jdbcTemplate.query(query, values.toArray(), resultSetExtractor);
like image 172
johnnyaug Avatar answered Jan 31 '26 05:01

johnnyaug



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!