4

我正在尝试在 grails 域类中实现 beforUpdate 事件,我需要审核记录域属性的旧值和新值。我看到我们可以使用isDirty检查或使用Domain.dirtyPropertyNameswhich 返回域中脏的属性列表。并getPersistentValue获取表中的旧值,以便我可以同时拥有这两个值..

为了实现这一点,我将在域类中使用 beforUpdate 事件并从那里调用日志服务,并将用户域的 id 传递给它。现在使用这个 ID 我可以在服务中获取用户实例,然后使用上面指定的方法检查是否有任何字段是脏的?或者当我实际在用户控制器的更新定义中进行更新时,我是否需要记录审核?

哪种方法更好?

我想确认这是否是正确的方法。
还有我需要注意的其他事项,例如:
1)如果属性是域对象引用而不是简单类型。
2)我需要注意的任何其他事情,比如不要刷新休眠会话,考虑在域类的服务调用中实现这一点。
问候,
普里扬克

编辑:我在要审核更新活动日志的用户域中的 beforeUpdate 事件中尝试了此操作。

def beforeUpdate = {
GraauditService service = AH.getApplication().getMainContext().getBean(''graauditService)
        service.saveUserUpdateEntry(this.id); // id property of User domain...
}

在 Service 的方法中,我这样做:

def saveUserUpdateEntry(Long id){
    User grauser = User.get(id);
    println ("user="+ grauser)
    println "Dirty Properties -: ${grauser.dirtyPropertyNames}"
    println "Changed value for firstName =  -: ${ grauser.firstName}"
    println "Database value for firstName =  -: ${ grauser.getPersistentValue('firstName')}"

    }

我尝试从 UI 对电子邮件、名字、姓氏进行更新,并在控制台上获取以下内容:

user=com.gra.register.User : 1
Dirty Properties -: [eMail, firstName, lastName]
Changed value for firstName =  -: sefser
Database value for firstName =  -: administer

user=com.gra.register.User : 1
Dirty Properties -: []
Changed value for firstName =  -: sefser
Database value for firstName =  -: sefser
possible nonthreadsafe access to session

我不知道:
1)为什么我会得到 2 套......该事件是在提交之前调用两次,在提交之后调用一次......??
2)如何删除或处理Hibernate异常(尝试在函数中使用withNew会话但没有区别

谢谢提前..

4

1 回答 1

0

Rather than using GORM event handlers for audit logging, use audit logging plugin. This will take away a lot of pain of yours.

Hope this helps.

or

If You want much finer control over what you are doing you should consider using a subclass of Hibernate's EmptyInterceptor. This will serve tow purposes for you

  1. Will give you much finer control over what and how you are doing the audit logging
  2. Will place all your logic for audit logging at one place, which will help you maintaining your code.

Click here to see the API for EmptyInterceptor.

Note: Hibernate does not ship any implementation in this class and also don't provide any subclass of this which might provide you the default behavior. So you will have to write a custom implementation.

于 2012-03-15T05:29:50.963 回答