0

I am adding Hibernate Envers to my Grails 3 project. I noticed that for one of my entities, which has an onLoad() event, the onLoad() event is never invoked for Envers revision entities.

How can I make sure this code is always invoked, even for historical revisions of this entity?

Use case:

I am working on a RESTful service using Grails 3 JSON views. One of my domain classes has a discriminator column, which must also be rendered in the JSON output so the consumer can tell what type it is. For this reason, the domain entity defines an onLoad() method which populates a transient property matching the discriminator type:

class MyChildDomainClass extends MyBaseDomainClass {
    void onLoad() {
        valueType = ValueType.STRING
    }

    static mapping = {
        discriminator value: ValueType.STRING
    }
}

This works fine for normal domain instances, but when I look up an entity revision from Envers' AuditQueryCreator, the audit query is not invoking the onLoad() method.

It seems like I could loop over the results and manually invoke onLoad(), but I was hoping there was a better way to fix this.

Thanks in advance!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
RMorrisey
  • 7,637
  • 9
  • 53
  • 71

2 Answers2

1

How can I make sure this code is always invoked, even for historical revisions of this entity?

I'm not well versed with Grails but these look very much like the typical JPA event lifecycle annotated events and these are likely methods that GORM (much like a JPA implementor) look for and invoke based on the lifecycle of an entity.

The big important take away here is that objects returned by the Envers Query API aren't entities. These objects are not managed by the persistence provider, so its important to clearly make that distinction as that influences a lot of persistence behavior expectations such as detached entities, entity lifecycle events, etc.

If there is some post-initialize or other lifecycle callbacks that you need to fire when fetching results from an AuditQuery, its on the user's code to make those distinctions and invoke those methods as needed.

Naros
  • 19,928
  • 3
  • 41
  • 71
  • Thanks for the reply. Does Envers have any kind of lifecycle hooks? I couldn't find it in the docs – RMorrisey Jan 18 '20 at 22:19
  • No, not at the moment but that doesn't mean we couldn't look into adding something like that if there really is such a need. – Naros Jan 20 '20 at 22:15
0

you could try changing the return type to "def", as stated in the doc here

class Person {
   String name
   Date dateCreated
   Date lastUpdated
   def onLoad() {
      log.debug "Loading ${id}"
   }
}
Gorille
  • 170
  • 12