【问题标题】:GORM inheritance custom IdentifierGORM继承自定义标识符
【发布时间】:2016-09-01 08:01:20
【问题描述】:

我目前正在创建一些域类的审计,并创建了一个 AuditingListener,它调用一个 ServiceMethod 来保存旧数据。

在这个服务方法中,我通过一些命名约定得到域类的审计类。

一切正常,但现在我正面临审计类的问题。 审计类从基础域类扩展,如下所示:

class Foo {
   String baaar
}    
class FooAudit extends Foo {
    Long auditId
    Date auditDate = new Date()
}

我的问题是我想在FooAudit 中保留Foo 的id 并拥有自己的id 属性。 在将创建审计条目的服务方法中,我得到了原始域类对象的所有属性的映射。 我想用这张地图设置FooAudit 的属性,但地图还包含Foooid 属性。

如果我按地图设置属性,例如

def auditEntry = new FooAudit()
auditEntry.properties = map

这会将FooAudit 的名称设置为与Foo 相同,但我想拥有自己的FooAudit 名称

如何将属性auditId 设置为FooAudit 的标识符?

【问题讨论】:

    标签: inheritance grails grails-orm


    【解决方案1】:

    例如,对于复制具有特殊情况的属性的情况,我有一个具有如下静态方法的类(也许它很有用...您可以按照自己喜欢的方式处理 id...)

    static def fillObjectProperties(def map, def obj, def excludeArray, def typeConvMap) {
        map.each {
            if (obj.hasProperty(it.key) && !excludeArray.contains(it.key)) {
                try {
                    if (it.value == null || it.value.size() == 0) {
                        obj.setProperty(it.key, null)
                    }
                    else if (typeConvMap.containsKey(it.key)) {
                        if (typeConvMap[it.key] == 'int') {
                            obj.setProperty(it.key, it.value as int)
                        } else if (typeConvMap[it.key] == 'BigDecimal') {
                            obj.setProperty(it.key, it.value as BigDecimal)
                        } else if (typeConvMap[it.key] == 'Date') {
                            Date date = new Date()
                            date.clearTime()
                            date.set(date: map[it.key + '_day'] as int, month: (map[it.key + '_month'] as int) -1, year: map[it.key + '_year'] as int)
                            obj.setProperty(it.key, date)
                        }
                    } else {
                        obj.setProperty(it.key, it.value)
                    }
                } catch(Exception ex) {}
            }
        }
    }
    
    static def copyObjectProperties(def source, def target) {
        target.metaClass.properties.each{
            if (it.name != 'metaClass') {
               it.setProperty(target, source.metaClass.getProperty(source, it.name))
            }
        }
        return source
    }
    

    【讨论】:

      【解决方案2】:

      也许您可以创建一个包含所有必要属性的基类?

      class FooBase{
          String baaar
      }
      
      class Foo extends FooBase{
      }
      
      class FooAudit extends FooBase {
          Long auditId
          Date auditDate = new Date()
      }
      

      【讨论】:

      • 如果我不需要FooAudit 中的Fooid,这可能会起作用,但在这种情况下我需要它。所以这对我不起作用......
      • 你是怎么做审计的?您可以在 Foo 的 beforeUpdate 事件中插入 FooAudit。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多