我正在尝试在Mule中创建一个流,允许在具有动态where语句的表中进行查询。 我们的想法是发送一个包含零个或多个条目的参数映射,然后从中构建一个查询字符串。
我使用hsqldb进行测试,并获得有关意外令牌的奇怪错误。
以下是流程:
<script:transformer name="extractParameters">
<script:script file="extractParameters.groovy" engine="groovy"/>
</script:transformer>
<flow name="datafetch.flow">
<vm:inbound-endpoint address="vm://datafetch" exchange-pattern="request-response"/>
<enricher target="#[variable:where-statement]">
<transformer ref="extractParameters"/>
</enricher>
<jdbc:outbound-endpoint connector-ref="datasource"
queryKey="parameterized-select"
exchange-pattern="request-response"
mimeType="text/plain">
<jdbc:query key="parameterized-select"
value="select * from ${datasource.table} #[variable:where-statement]"/>
</jdbc:outbound-endpoint>
<json:object-to-json-transformer name="CaseInsensitiveHashMapToJson"/>
</flow>
richher是一个groovy脚本,它将json结构转换为where-statement字符串:
import groovy.json.JsonSlurper
def input = new JsonSlurper().parseText(payload)
def parameters = input?.get("parameters")
def result = ""
if(parameters==null) return result
def where = parameters.inject([]) { list, entry -> list << "${entry.key}=${entry.value}"}.join(" AND ")
if (where.isEmpty()) return result
result = "where " + where
return result
发送空参数会导致richher生成空字符串,错误为:
1. unexpected token: ? (org.hsqldb.HsqlException)
org.hsqldb.error.Error:-1 (null)
2. unexpected token: ?(SQL Code: -5581, SQL State: + 42581) (java.sql.SQLSyntaxErrorException)
org.hsqldb.jdbc.Util:-1 (null)
3. unexpected token: ? Query: select * from TABLE1 ? Parameters: [](SQL Code: -5581, SQL State: + 42581) (java.sql.SQLException)
org.apache.commons.dbutils.QueryRunner:540 (null)
发送一个参数(C1 = 0)会导致更丰富的产生字符串“where C1 = 0”,错误是:
1. unexpected token: ? (org.hsqldb.HsqlException)
org.hsqldb.error.Error:-1 (null)
2. unexpected token: ?(SQL Code: -5581, SQL State: + 42581) (java.sql.SQLSyntaxErrorException)
org.hsqldb.jdbc.Util:-1 (null)
3. unexpected token: ? Query: select * from TABLE1 ? Parameters: [where C1=0](SQL Code: -5581, SQL State: + 42581) (java.sql.SQLException)
org.apache.commons.dbutils.QueryRunner:540 (null)
因此,看起来查询需要的不是我写的#[variable:where-statement]
那么,我需要为where-statement
变量提供什么才能使其正常工作?
或者,是否有其他方法来指定它?
答案 0 :(得分:2)
我试过这种方式并且有效:
<scripting:transformer doc:name="Groovy">
<scripting:script engine="Groovy"><![CDATA[def q ="select * from myTable where 1=1 ";
if(payload.containsKey('param1')) q = q + " And mycolumn = " + payload.param1;
payload.put('dynamicWhere', q);
return payload;]]></scripting:script>
</scripting:transformer>
<outbound-endpoint exchange-pattern="request-response" connector-ref="ConnectorDb" doc:name="Database" address="jdbc://#[payload.dynamicWhere]" />
...