VB_
VB_

Reputation: 45692

Hibernate: check which entity's fields are modified

What I have:

I've Hibernate entity, which contains many non-transient fields, including collections. User can update each field separately or some group of fields at once.

What a challange:

In handler I should check what field of the entity have been changed:

public void handle(Entity newVersion) {
  Session session = sessionFactory.openSession();
  Entity oldVersion = (Entity) session.get(Entity.class, entity.getId());
  List changedFields = compareChanges(oldVersion, newVersion);  //HOW TO CHECK WHICH FIELDS ARE CHANGED?
}

I want to do it for security and notification reasons. Means:

  1. Not all users can modify all fields
  2. I should notify specific users in specific ways on some fields change.

What a problem:

I get very ugly code. Actually I iterate throught all fields/collections and call equals method.

Question:

May be Hibernate provide more elegant way to check what fields have been modified? How?

P.S.

@victorantunes provide a solution, but it seems too comprehensive for me. May be some alternatives?

Upvotes: 28

Views: 35713

Answers (3)

Alok
Alok

Reputation: 301

What you can do is make a Hibernate Interceptor that would act like a trigger in the events like create, modify and update. http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/events.html so that any point before the given entity is about to be modified and persisted, 1.You can check whether the user has the access (you can get username from session or database) to modify the particular field and accordingly you can grant the access to save or update. 2.You can notify the other user about only when the entity is modified.

By this way you can make a new session-scope Interceptor in spring's implementation ofHibernate 4 Session session = s.withOptions().interceptor(new YourInterceptor().openSession();

Upvotes: 19

Bimalesh Jha
Bimalesh Jha

Reputation: 1504

I think Hibernate interceptors can be used http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/events.html you can compare old and new values of the entity fields.

Upvotes: 1

victorantunes
victorantunes

Reputation: 1169

If what you want is to be able to check which fields have been modified, it may be worth taking a look at Hibernate Envers, which works as an auditing tool that creates a separate table containing the changes that were made to your business logic table.

http://www.jboss.org/envers

I started using it for some internal auditing and it's really simple and works like a charm.

Here's a quick tutorial:

https://thenewcircle.com/s/post/115/easy_auditing_versioning_for_your_hibernate_entities_with_envers

Upvotes: 8

Related Questions