使用GORM对集合执行脏检查

时间:2012-05-28 20:49:37

标签: grails gorm

我试图以一种可以触发新对象创建的方式检测集合的更改。例如,库存有许多项目。项目具有名称和数量。我可以使用脏检查检测项目的添加/删除。

//Detecting add/change
inventoryInstance.items.isDirty()

我很难识别对相关Item对象(名称,数量)的更改以及项目中的订单更改。 isDirty()似乎没有标识这些更改。我正在使用Grails 1.3.7,我使用grails数据绑定通过HTML表单和索引字段名称(items [0] .name,items [0] .quantity)。有没有人有建议的解决方案或替代方法?

示例域类:

class Inventory {
  List items = new ArrayList()

  static hasMany = [items:Item]
  static constraints = {
    items(size:0..10)
  }
  static mapping = {
    items cascade: 'all-delete-orphan'
  }
}

class Item {
  String name
  Integer quantity = 1
  Boolean deleted = false

  static transients = ['deleted']
  static belongsTo = Inventory
  static constraints = {
    name blank:false
    quantity size:1..100
  }
}

控制器

def inventoryInstance = Inventory.get(params.id)

if( inventoryInstance ) {
  inventoryInstance.properties = params

  // Check for add/removes, this works.
  def isDirty = inventoryInstance.items.isDirty()

  if(!isDirty) {
    // Check items in list for changes, does not work..
    inventoryInstance.items.each { item ->
      if(item.dirtyPropertyNames) isDirty = true
    }
  }

  if(isDirty) {
    //do something...
  }

  inventoryInstance.save(flush:true)
}

1 个答案:

答案 0 :(得分:0)

这是我的代码,它与您要求的内容类似:

        def taskChanges = []
        requestInstance?.tasks?.each { task ->
            taskChanges << [task,
                    task?.dirtyPropertyNames?.collect {name ->
                        def originalValue = task.getPersistentValue(name)
                        def newValue = task."$name"
                        log.debug "$name : old:: $originalValue , new:: $newValue ."
                        [(name): [originalValue: originalValue, newValue: newValue]] //returned and added to taskChanges list
                    }
            ]
        }