Hibernate Envers with Grails 2.1.0

Monday, August 6, 2012

Our client requires that every entity in his Grails application has to be audited with detailed information: who and when did exactly what? It is a perfect opportunity to use Hibernate Envers! It turned out not as straightforward as I thought, so I want to share my experience with you.

Introduction

I use latest release of Grails with version 2.1.0. I've created a sample application on github for you as an example - SpOOnman/enversdemo. All files and techniques mentioned here can be found inside it. If you have other experiences with Grails and Envers working together, please share in comments.

Grails Envers plugin

First I've searched for a Grails plugin. I've found one outdated on google code and a (more modern) on github. This plugin is created by Lucas Ward and it has great introductionary blog post by author. This is a great place to start.

Unfortunately Lucas Ward's plugin supports Grails up 1.3.7 and it comes with outdated Envers version. I've searched through forks and I've found most up-to-date fork by Matija Folnovic: https://github.com/mfolnovic/grails-envers-plugin. It supports Grails 2.1 out of the box. Edit: Matija pointed out that credit should go to Jay Hogan and Damir Murat for their work on upgrading Envers plugin to Grails 2.

Update (16.12.2013): As Glenn Filson pointed out in comments, envers plugin is now packaged in Grails central repository with a version 2.1.0. So packaging a plugin may be skipped, but remember to add plugin to BuildConfig.groovy wither way. Thanks for that Glenn!

Matija's plugin is not packaged nor published so you have to package it by yourself:

Copy grails-envers-0.3-SNAPSHOT.zip (and rename to envers-0.3-SNAPSHOT.zip) to your application's lib diretory or publish to your company maven repository if you have one. Last step is to include a plugin in your BuildConfig.groovy:

Audit with Envers!

It's really easy to audit all entities with Envers. All you have to do is to use @Audit annotation on entities. SpOOnman/enversdemo audits Hotels and Bookings:

Envers plugin comes with some handy methods. For example Hotel.findAllRevisions() returns list of previous revisions. Once again I recommend a great blog post by Lucas Ward with many examples.

Grails and transactions

Grails has some glitches working with Envers. Envers is closely tied to database transactions. This means that it runs its listeners at the transaction end, when session is flushed. This is not always the case in Grails and it's the cause of some problems. You need to make some small modifications to your application to be sure that Envers works fine.

  • controllers - you need to annotate your controllers (or separate controller methods) with @Transactional and for every save you need to flush a session manually, e.g. save(flush: true). Otherwise Envers may not be notified.
  • services in Grails are transactional by default. However you mey explicitily set them with static transactional = true to be sure that this is not altered. I recommend to use session flushing on every save as well.
  • BootStrap.groovy script is not transactional. If you want Envers to audit your changes in this script you need to wrap your inserts with transactions. You can achieve it by using withTransaction closure. You need session flushing too. Take a look at SpOOnman/enversdemo BootStrap.groovy for an example.
  • integration tests wrap every test in a separate transaction that is rolled back at the end of a test, hence Envers won't work here. You need to disable wrapped transactions with static transactional = false. Remember that your changes are commited to database. To fulfill a contract of an empty database for every test you need to take care of cleaning up a database manually. Here is my sample integration test.

Add User to revision entities

By default Envers comes with a DefaultRevisionEntity class and creates its instance for every change on audited instance. It keeps information about entity revision, date and modification type. It lacks information about a user that made a change. I want to extend it.

There is already a code inside a plugin (here and here) but it's not packaged with a plugin itself. I guess it's because it adds dependency to Spring Security. This not a problem for me since I already use Spring Security plugin already in my application. I decided to add missing classes inside my application.

First I need a domain class - UserRevisionEntity. New instance of this class is created for every revision saved by Envers. It is a simple domain class with some extra annotations:

Notice that I've made currentUser field nullable. There may be some actions that doesn't require user to be logged in. Also, there is no user while executing BootStrap.groovy script.

Annotations @RevisionNumber and @RevisionTimestamp are required by Envers as described in documentation. @RevisionEntity annotation configures Envers to use non-default listener - SpringSecurityRevisionListener. It looks simple:

SpringSecurityRevisionListener's newRevision method fills each UserRevisionEntity instances with currently logged User.

Configuration

Envers offers some configuration options listed on documentation page. Options can be set in persistence.xml. However in Grails there is no persistence.xml. You can add it (and Grails supports it), but I've found other way to configure properties. I use System.setProperties to configure Envers and I place it in grails-app/conf/spring/resources.groovy. This is an example to change Envers tables' prefix and suffix:

Testing

Testing Envers makes sense only with Grails integration tests. As I've mentioned earlier you must disable transactions that wrap your tests in order for Envers listeners to work. Also make sure you use withTransaction, session flushing and you've marked your controllers as @Transactional. There rules all stand in integration tests too. Example integration test can look like this:

Summary

Hibernate Envers does a great job auditing my application. It is easy to use, despite all the small glitches I've mentioned here. Special thanks to plugin authors that package Envers library in a plugin that can be used out of the box. I really recommend it! It would be great to hear all your thoughts on Envers and Grails working together so I can improve this post for others too.

Update 12.04.2013

Lucas Ward has posted updaate entry on Grails Hibernate Envers plugin here: http://www.lucasward.net/2013/04/grails-envers-plugin-update.html. Thanks!

26 comments:

  1. Thanks for writing and sharing a great post!

    Why not publish the Grails Envers plugin to public Grails plugins repository?

    ReplyDelete
    Replies
    1. Thanks. I will pass this suggestion to plugin maintainer.

      Delete
  2. Thanks for shout-out and the upgrade work. I quite simply haven't gotten around to upgrading our app to grails 2 yet, so I didn't upgrade any of the work I had done on the envers plugins.

    ReplyDelete
  3. Very useful post Tomasz, after looking at the plugins available for auditing, my search path took me to hibernate-envers and finally to this post. Thanks for taking the time to write it.

    ReplyDelete
  4. If there are multiple data sources defined in DataSource.groovy, the plugin is not saving any data in the audit tables. Any suggestions?

    ReplyDelete
  5. Hello,

    Seems field level annotations are not working:
    --
    @Audited
    class Booking {

    @NotAudited
    String surname
    Date startDate
    Integer daysCount

    static constraints = {
    }

    static belongsTo = [hotel: Hotel]
    }
    --

    Code above does not prevent surname from being audited.

    ReplyDelete
  6. --
    class Booking {

    @Audited
    String surname
    Date startDate
    Integer daysCount

    static constraints = {
    }

    static belongsTo = [hotel: Hotel]
    }
    --

    This also not works as expected - according to envers documentation it should make only one field surname audible for Booking. It makes Booking not audible at all.

    ReplyDelete
  7. I found workaround for issue with field annotations in another blog - http://www.lucasward.net/2011/04/grails-envers-plugin.html?showComment=1305581292932#c7672244570118132937

    ReplyDelete
  8. In groovy @Audited should be placed before getter and getter should be defined explicitly for this case.
    The fix for code above is :

    class Booking {

    String surname
    Date startDate
    Integer daysCount

    static constraints = {
    }

    static belongsTo = [hotel: Hotel]
    }

    @Audited
    String getSurname() {
    return surname
    }

    ReplyDelete
  9. Thanks for taking the time to write this post and publish the plugin in the Grails plugin repo. As Lucas said earlier, I have been meaning to do this myself, but real life keeps getting in the way.

    ReplyDelete
  10. Thanks a lot for this great piece of information. Was also meaning to do this myself starting just before googling and finding this awesome post.

    ReplyDelete
  11. Was really helpful. Thanks so much.

    ReplyDelete
  12. I need to audit specific fields in my domain class. I've used @Audited on getter methods and it works fine.

    @Audited
    String getDescription() {
    return description
    }

    I also have relation defined as:

    static hasMany = [tags: Tag]

    that needs to be audited. How do i handle this?

    ReplyDelete
    Replies
    1. Try with:

      @Audited
      static hasMany = [tags: Tag]

      Does it work?

      Delete
    2. That didn't work but the following worked:

      Set tags
      static hasMany = [tags: Tag]

      @Audited
      Set getTags() {
      return tags
      }

      Delete
    3. Thank you for posting working example.

      Delete
  13. I am using @Audited on getter methods instead of at class level for auditing specific properties only. However i am unable to use any of the dynamic finder methods findAllRevisionsById() etc. It says cannot resolve property revision. If i annotate the class @Audited, it works.
    Is there a work around for this without annotating the class? One option is using AuditReader and write your own logic.

    ReplyDelete
  14. Thanks...
    But Is it possible to add additional column having user details like username in audited table. So i can identify that which user did the transaction. Please help me.
    Thanks in advance.

    ReplyDelete
  15. I finally got around to tackling some of this: http://www.lucasward.net/2013/04/grails-envers-plugin-update.html

    ReplyDelete
    Replies
    1. Thank you! I've updated my post with your link.

      Delete
  16. It looks like the plug-in has now been pushed live to Grails central repository. You can simply add to your plug-in section in BuildConfig.groovy:

    compile ":envers:2.1.0"

    ReplyDelete
  17. This comment has been removed by the author.

    ReplyDelete
  18. I stumbled upon this blog, Lukas Ward's Blog, a few community sites, but I could not get a clear answer on how to implement the following queries using the envers plugin:
    - When was the domain object created? E.g. when was an instance of 'Hotel' created?
    - What is the last modified date of some domain object? E.g. when was an instance of 'Hotel' last modified?
    - Which 'user' has created the object? E.g. who has created a particular instance of a 'Hotel' domain class?
    - Which 'user' has last modified the object? E.g. who has last modified a particular instance of a 'Hotel' domain class?
    - Find all instances of a domain class created by some 'user'? E.g. find all instances of domain class 'Hotel' created by the current user.

    Also, I would like to know if it is possible to use the audit methods inside named queries.

    ReplyDelete