【发布时间】:2014-03-31 04:33:10
【问题描述】:
我有 4 个对象(域类的实例)称为出租车,放置在属性allocatedTaxi 下的一个名为moveRequest 的对象中。
类如下所示:
class MoveRequest{
Taxi allocatedTaxi
Zone destinationZone
Integer destination
String microDestination
String targetType = ""
String targetName = ""
Zone currentTaxiZone
Taxi obstructingTaxi
Taxi boardedTaxi
String state = "pending"
Boolean requestedSpecific
Date dateCreated
static constraints = {
currentTaxiZone(nullable: true)
obstructingTaxi(nullable: true)
boardedTaxi(nullable: true)
}
static mapping = {
version false
}
}
class Taxi {
String name
Integer position
Double voltage
Boolean busy
Integer orderNumber
static belongsTo = [rail: Rail]
static mapping = {
version false
}
static constraints = {
name blank: false
}
}
现在,在迭代 moveRequests 时,我使用如下函数中的 sql 语句更新出租车对象的位置属性:
def updateTaxiPosition(def taxiName, def millimeters){
def config = grailsApplication.config
def sql = Sql.newInstance(config.grails.databaseURL, config.grails.databaseUsername, config.grails.databasePassword, config.grails.databaseDriverClassName)
sql.getConnection().setAutoCommit(true)
sql.execute("UPDATE taxi SET position= ? WHERE name = ?", [millimeters, taxiName])
sql.close()
}
现在,另一种方法是使用这行代码:
moveRequest.allocatedTaxi.position = millimeters
但是,由于我需要使用直接 sql 快速更新它,因为它会自动更新出租车位置。现在,当我尝试访问更改的位置时,问题就出现了。我只能访问旧位置,即使数据库中的位置已更改,当我尝试这样做时:
println("taxi position: " + moveRequest.allocatedTaxi.position)
我在更新位置属性之前获取旧值。现在我尝试像这样刷新 moveRequest 实例:
def refreshMoveRequestInformation(def moveRequest){
def config = grailsApplication.config
def sql = Sql.newInstance(config.grails.databaseURL, config.grails.databaseUsername, config.grails.databasePassword, config.grails.databaseDriverClassName)
sql.getConnection().setAutoCommit(true)
def row = sql.rows("SELECT * FROM taxi WHERE id=?", [moveRequest.allocatedTaxi.id])
println("row -> taxi name: " + row.name + ", taxi position: " + row.position)
sql.close()
def newPosition = null
row.each{
newPosition = it.position
}
moveRequest.allocatedTaxi.position = newPosition
}
还有这样的:
def refreshMoveRequestInformation(def moveRequest){
def taxi = Taxi.get(moveRequest.allocatedTaxi.id)
println("1 - new taxi name: " + taxi.name + ", taxi position: " + taxi.position)
taxi.refresh()
println("2 - new taxi name: " + taxi.name + ", taxi position: " + taxi.position)
println("move request -> taxi name: " + moveRequest.allocatedTaxi.name + ", taxi position: " + moveRequest.allocatedTaxi.position)
return moveRequest
}
但似乎都不起作用。即使行实例显示新值,我也会不断获得旧值。如何更新 moveRequest 实例(我的意思是从数据库重新加载)它的分配出租车属性(或更准确地说,位置属性)??
【问题讨论】: