如何将XML文件中的条目视为GString并使groovy仍然';评估';信息技术
下面的第一个示例说明了工作代码。我想进一步了解工作代码,并将SQL存储在XML文件中。然而,一旦我从XML文件中读取它,我似乎就无法让groovy再将SQL语句作为GString来处理了 以下是工作示例:如何将XML文件中的条目视为GString并使groovy仍然';评估';信息技术,groovy,Groovy,下面的第一个示例说明了工作代码。我想进一步了解工作代码,并将SQL存储在XML文件中。然而,一旦我从XML文件中读取它,我似乎就无法让groovy再将SQL语句作为GString来处理了 以下是工作示例: private void testRefCursors(){ //object owner paramter String owner = 'HR'; //Block of Oracle SQL to execute, returning 4 parameters
private void testRefCursors(){
//object owner paramter
String owner = 'HR';
//Block of Oracle SQL to execute, returning 4 parameters
def sqlBlock =
"""
declare
type crsr is ref cursor;
tables crsr;
objects crsr;
begin
select count(*) into ${Sql.INTEGER} from all_tables where owner= ${owner} ;
open tables for select * from all_tables where owner= ${owner} ;
${Sql.resultSet OracleTypes.CURSOR} := tables;
select count(*) into ${Sql.INTEGER} from all_objects where owner= ${owner} ;
open objects for select * from all_objects where owner= ${owner};
${Sql.resultSet OracleTypes.CURSOR} := objects;
end;
"""
//note the order below, is the order of the 'types'
//in the SQL block used in the closure as parameters.
sqlSEDREF.call(sqlBlock){
t,user_tables,o,user_objects ->
println "found ${t} tables from a total of ${o} objects"
user_tables.eachRow(){x ->println "table:${x.table_name}"}
user_objects.eachRow(){println "object:${it.object_name}"}
}
}
现在,当我将示例更改为从XML文件读取SQL块时;我不知道如何(或是否可能)将该值视为GString:
private void testRefCursors(){
//object owner paramter
String owner = 'HR';
def configFile = new File("config.xml");
config = new XmlSlurper().parse(configFile);
// FAILURE HERE -
GString sqlBlock = config.'sql-test-cursors'
//note the order below, is the order of the 'types'
//in the SQL block used in the closure as parameters.
sqlSEDREF.call(sqlBlock){
t,user_tables,o,user_objects ->
println "found ${t} tables from a total of ${o} objects"
user_tables.eachRow(){x ->println "table:${x.table_name}"}
user_objects.eachRow(){println "object:${it.object_name}"}
}
}
返回的错误是由于无法使用SQL.call(GString,Closure)的GString实现造成的:
捕获:
groovy.lang.MissingMethodException:否
签名
方法:groovy.sql.sql.call()是
适用于参数类型:
(java.lang.String,tools.UAT$\u testRefCursors\u closure2)
我目前的解决方法可能是从config.xml转换为config.groovy文件,并从.groovy文件而不是xml中读取gstring。非常感谢您的建议。我想您可以试试
var sqlBlock = config['sql-test-cursors'].text()
这可能会返回一个GString XML文件不会返回GString,因为GString是由groovy编译器在编译时构造的。当解析XML文件时,得到的是字符串,而不是已编译的Groovy可执行文件 如果您真的想在XML文档中嵌入groovy代码(这正是您在这里真正想要做的),那么您应该从以下内容开始:。基本上,您可以读入SQL并将其视为嵌入式groovy脚本 另一种方法(我在遇到类似问题时采用的方法)是使用MessageFormat替换XML中的值
def s = '<sql><query-name>Some SQL</query-name>
<query>
select * from {0}
</query>
</sql>'
这不会评估GString。此后,我找到了一些关于使用GroovyShell和TemplateEngine实现此功能的资料。还有一个关于我正在做的事情的功能请求已经提交给JIRA,地址:hmm。。所以我想知道这个对象是来自text()的什么类。。我得去看看。很抱歉,我会看看能不能让它工作。我想我现在感到困惑的是,唯一接受闭包的SQL.call方法是GString版本:Wait。我刚刚注意到这个方法签名:call(字符串sql、列表参数、闭包)
assert java.text.MessageFormat (xml.sql.query.text()).format ('dual')
== 'select * from dual'