How does groovy's addBatch(map) work for Sql.withBatch?

170 Views Asked by At

I'm trying to call groovy.sql.Sql.batch from a statically typed language.

I succeed in calling addBatch on the callback object ps with a parameter of type List. This works well for statements like insert into TABLENAME(a, b, c) values (?, ?, ?).

To cite the documentation:

Named parameters (into maps or domain objects) are also supported:

def updateCounts = sql.withBatch(20, 'insert into TABLENAME(a, b, c) values (:foo, :bar, :baz)') { ps ->
    ps.addBatch([foo:10, bar:12, baz:5])  // map
    ps.addBatch(foo:7, bar:3, baz:98)     // Groovy named args allow outer brackets to be dropped
    ...
}

So, I thought to also support using batch updates for Maps. The problem is, that the callback parameter of type BatchingPreparedStatementWrapper does not provide a method addBatch(Map), but only overloads addBatch(Object[]), addBatch(List), addBatch(String).

How can Sql.withBatch be used with Map parameters from kotlin or java? And how does it actually work in groovy without throwing NoSuchMethodError, MissingMethodException or whatever?

1

There are 1 best solutions below

1
On BEST ANSWER

in groovy following code:

def f(Object[] p){
    println p
}


f( a:1, b:2, c:3 )

works fine and prints:

[[a:1, b:2, c:3]]

so, if you have function f(Object[] x), then f(a:123) equals to f( [ [a:123] ] )

this means that from java following should work:

Map params = new HashMap();
params.put("a", 123);

ps.addBatch( new Object[]{ params } );