我想在Map查询中使用Map的键集作为列表参数:
query = "select contentid from content where spaceid = :spaceid and title in (:title)"
sql.eachRow(query, [spaceid: 1234, title: map.keySet().join(',')]) {
rs ->
println rs.contentid
}
我可以使用单个值,但不能使用任何集或列表。 这是我到目前为止所尝试的:
map.keySet().join(',')
map.keySet().toListString()
map.keySet().toList()
map.keySet().toString()
地图使用字符串作为键
Map<String, String> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
另外,我没有收到错误。我没有打印任何打印结果,如果有空结果。
答案 0 :(得分:2)
你的任命不会给出预期的结果。
逻辑上,您使用的是谓词,例如
title = 'value1,value2,value3'
这就是为什么你没有例外但也没有数据的原因。
快速搜索提供了一些证据,即在Groovy SQL中可以将集合映射到IN列表。 请检查here和here
所以很可能你必须以适当的长度定义IN列表并分配数组中的值。
title in (:key1, :key2, :key3)
无论如何这样的事情很好:
数据强>
create table content as
select 1 contentid, 1 spaceid, 'AAA' title from dual union all
select 2 contentid, 1 spaceid, 'BBB' title from dual union all
select 3 contentid, 2 spaceid, 'AAA' title from dual;
Groovy脚本
map['key1'] = 'AAA'
map['key2'] = 'BBB'
query = "select contentid from content where spaceid = :spaceid and title in (${map.keySet().collect{":$it"}.join(',')})"
println query
map['spaceid'] = 1
sql.eachRow(query, map) {
rs ->
println rs.contentid
}
<强>结果强>
select contentid from content where spaceid = :spaceid and title in (:key1,:key2)
1
2
关键步骤是使用experssion map.keySet().collect{":$it"}.join(',')
注意强>
您可能还想检查地图的大小并处理大于1000的情况,这是单个IN列表的Oracle限制。
答案 1 :(得分:0)
它对我来说有点适应,我将地图添加为第二个参数。
def sql = Sql.newInstance("jdbc:mysql://localhost/databaseName", "userid", "pass")
Map<String,Long> mapProduitEnDelta = new HashMap<>()
mapProduitEnDelta['key1'] = 1
mapProduitEnDelta['key2'] = 2
mapProduitEnDelta['key3'] = 3
produits : sql.rows("""select id, reference from Produit where id IN (${mapProduitEnDelta.keySet().collect{":$it"}.join(',')})""",mapProduitEnDelta),
显示ID为1、2、3的3种产品(列和产品表中的值)