将结果行强制到对象中 [英] Coerce result row into object
问题描述
我知道我可以使用像Node.list()这样的东西来做到这一点,但我最终将用一个相当复杂的存储过程来替换getnodes(),它创建临时表并执行一些优化的sql fu。但是现在我只是在处理grails交互。
所以在MySQL方面,我有以下存储过程:
CREATE DEFINER =`root` @ 255.255.255.255` PROCEDURE`getnodes`()
BEGIN
select * from node;
END
在grails控制器上,我有以下内容:
def nodes = new ArrayList< Node>()
//收集所有返回的节点
sql.eachRow( {call getnodes()}){
nodes.add(它为节点)
}
println节点大小为:+ nodes.size()
nodes.eachWithIndex {d,i - >
println$ i:$ d
}
我的计划是然后将节点传递给视图。
问题是它爆炸了:
<$ p $ (这是节点)
这甚至可能吗?我的意思是这应该只是胁迫吧?我做错了什么?
不,它不应该只是胁迫。关于以下内容:
sql.eachRow({call getnodes()}){
nodes.add(它作为Node)
}
它的类型 code>是GroovyRowResult,因此
它作为Node
将调用 GroovyRowResult.asType(Node.class)
因此,除非此方法的作者专门处理此转换,否则此强制将失败。由于从GroovyRowResult转换到Node是相当模糊的,我不认为应该合理预期这种情况的处理。
一个显而易见的解决方案是自己完成转换:
sql.eachRow({call getnodes()}){GroovyRowResult it - >
Node node = // TODO:将其转换为Node的代码
nodes.add(node)
}
或者,您可以使用元编程来覆盖的
,这样它也可以处理到Node的转换。 asType
方法GroovyRowResult
Is there a way to coerce the result row gotten from calling a stored procedure into a specific object so I can pass just a list of that object into the view?
I know I can use things like Node.list() to do this, but I am eventually going to replace getnodes() with a fairly complicated stored procedure that creates temp tables and does some optimised sql fu. But for now I am just working on the grails interaction.
So on MySQL side I have the following stored procedure:
CREATE DEFINER=`root`@`255.255.255.255` PROCEDURE `getnodes`()
BEGIN
select * from node;
END
On the grails controller I have the following:
def nodes = new ArrayList<Node>()
// collect all the nodes returned
sql.eachRow("{call getnodes()}") {
nodes.add(it as Node)
}
println "Nodes size is: " + nodes.size()
nodes.eachWithIndex { d, i ->
println "$i : $d"
}
My plan is to then pass the nodes to the view.
The problem is that it blows up on the line:
nodes.add(it as Node)
Is this even possible? I mean this should just coerce right? What am I doing wrong?
No, it shouldn't "just coerce". Regarding the following:
sql.eachRow("{call getnodes()}") {
nodes.add(it as Node)
}
The type of it
is GroovyRowResult, so it as Node
will call GroovyRowResult.asType(Node.class)
So this coercion will fail unless the author of this method specifically handles this conversion. As converting from GroovyRowResult to Node is fairly obscure, I don't think one should reasonably expect this case to be handled.
An obvious solution is to do the conversion yourself:
sql.eachRow("{call getnodes()}") {GroovyRowResult it ->
Node node = // TODO: Code to convert it to a Node
nodes.add(node)
}
Alternatively, you could use meta-programming to override the asType
method of GroovyRowResult
such that it also handles conversion to Node.
这篇关于将结果行强制到对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!