用groovy从对象更新SQL [英] Updating SQL from object with groovy

查看:380
本文介绍了用groovy从对象更新SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



看起来您应该能够更新这些地图中的值并将其写入退出,但我无法找到Groovy中的任何内容来允许我这样做。



我正在考虑编写一个允许我编写修改过的映射的例程通过遍历其中一个结果对象的字段,获取每个键/值对并使用它们来创建适当的更新语句,但这可能很烦人,所以我想知道是否有其他人已经做了这个或者它是否已经可用在groovy。

它似乎只是几行代码,所以我宁愿不为此引入休眠。

 
def rows = sql.rows(query)
rows [0] .name =newName
update(sql,rows [0])

更新第一个人数据库中的名称。任何人都看到/创建了这样的怪物,或者像这样的东西已经内置到Groovy Sql中,我只是想念它?



(我想你可能不得不指出到更新方法哪个字段是关键字段,但这是可行的...)

解决方案使用 rows 方法将实际读出所有值到 List > GroovyRowResult so如果不创建更新方法就不可能创建更新方法。



在通用情况下不可能这样做,因为您的 query 可以包含连接或者是一个聚集等的列引用。



如果您从单个表中进行选择,然而, Sql.eachRow 方法并将 ResultSet 设置为可更新的,您可以使用基础的 ResultSet 界面在迭代时进行更新:

  sql.resultSetConcurrency = ResultSet.CONCUR_UPDATABLE 
sql.resultSetType = ResultSet.TYPE_FORWARD_ONLY
sql.eachRow(query){row - >
row.updateString('name','newName')
row.updateRow()
}

根据您使用的数据库/驱动程序,您可能无法创建可更新的 ResultSet


When you read in a result set in Groovy it comes in a collection of maps.

Seems like you should be able to update values inside those maps and write them back out, but I can't find anything built into groovy to allow me to do so.

I'm considering writing a routine that allows me to write a modified map by iterating over the fields of one of the result objects, taking each key/value pair and using them to create the appropriate update statement, but it could be annoying so I was wondering if anyone else had done this or if it'sa vailable already in groovy.

It seems like just a few lines of code so I'd rather not bring in hibernate for this. I'm just thinking a little "update" method that would allow:

def rows=sql.rows(query)
rows[0].name="newName"
update(sql, rows[0])

to update the first guy's name in the database. Anyone seen/created such a monster, or is something like this already built into Groovy Sql and I'm just missing it?

(I suppose you may have to point out to the update method which field is the key field, but that's doable...)

解决方案

Using the rows method will actually read out all of the values into a List of GroovyRowResult so it's not really possible to update the data without creating an update method like the one you mention.

It's not really possible to do that in the generic case because your query can contain joins or a column reference that is an aggregate, etc.

If you're selecting from a single table use the Sql.eachRow method however and set the ResultSet to be an updatable one, you can use the underlying ResultSet interface to update as you iterate through:

sql.resultSetConcurrency = ResultSet.CONCUR_UPDATABLE
sql.resultSetType = ResultSet.TYPE_FORWARD_ONLY
sql.eachRow(query) { row ->
    row.updateString('name', 'newName')
    row.updateRow()
}

Depending on the database/driver you use, you may not be able to create an updatable ResultSet.

这篇关于用groovy从对象更新SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆