Hibernate - Envers & # 8594; audit / attribute version, but only if the value is changed

I have a problem with Hibernate - Envers. I have a domain object with only one verified status attribute, which can be one of the numbers 0,1,2,3,4,5.

 @Entity public class Item { ... @Audited private int status; ... other variables, setter/getter, ... } 

Now everything in Envers and Hibernate works. By creating a new Item object and adding it to the database, the row is inserted into the Item_AUD database Item_AUD .

But now I have a problem with updating it. My update on the Hibernate Dao implementation looks like this:

 public void updateItem(Item i) { SessionFactory sessionFac = HibernateUtility.getSessionFactory(); Session s = sessionFac.getCurrentSession(); Transaction trans = s.beginTransaction(); s.update(i); s.flush(); trans.commit(); } 

With every update, this is printed on my console:

 Hibernate: update Item set amount=?, description=?, status=? where id=? Hibernate: insert into REVINFO (REVTSTMP) values (?) Hibernate: insert into Item_AUD (REVTYPE, status, id, REV) values (?, ?, ?, ?) 

But the problem is that I only want to insert a line in REVINFO and Item_AUD if the status number has changed!

For example: I change the description element, perform an update with an updateItem call, and then Envers writes the new revision to the audit tables. But I do not want this behavior.

What I want: only if the status value is changed, Envers should write database records to audit tables.

But how can I do this?

Best regards, Tim.

+4
source share
1 answer

To do this, you need to extend the AuditEventListener and override its methods.

  public class EnversListener extends AuditEventListener { @Override public void onPostInsert(PostInsertEvent event) { Object o = event.getEntity(); if (o instanceof Item) { Item currentItem = (Item) o; Item previousItem = findItemById(currentItem.getId()); if(previousItem != null) if (currentItem.getStatus() != previousItem.getStatus()) super.onPostInsert(event); } else { super.onPostInsert(event); } } @Override public void onPostDelete(PostDeleteEvent event) { super.onPostDelete(event); } @Override public void onPostRecreateCollection(PostCollectionRecreateEvent event) { super.onPostRecreateCollection(event); } @Override public void onPostUpdate(PostUpdateEvent event) { super.onPostUpdate(event); } @Override public void onPreRemoveCollection(PreCollectionRemoveEvent event) { super.onPreRemoveCollection(event); } @Override public void onPreUpdateCollection(PreCollectionUpdateEvent event) { super.onPreUpdateCollection(event); } } 

If necessary, you can add your own restrictions to other overridden methods. The path to the listener class inside hibernate.cfg.xml must be configured accordingly.

+5
source

Source: https://habr.com/ru/post/1334335/


All Articles