Reputation: 501
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?
Upvotes: 4
Views: 1572
Reputation: 187499
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.
Upvotes: 3