Robert Franz
Robert Franz

Reputation: 543

Is there a way to track changes of an entity?

I have an entity. This entity is modified within a transaction. But at some point I want to know the changes to this entity that were made during the transaction. The reason for that is to trigger an differential export of the changes to the entity. I already developed this "solution":

public void triggerExport(A a)
{
    em.detach(a);
    A result = em.find(A.class, a.internId);

    doExport(a, result);
    em.merge(a);

}

I'm not sure if this really is a practicable way to do this. It causes extra database interaction for each comparsion of this entity. What do you think? Is there a better way?

Upvotes: 1

Views: 2401

Answers (3)

James
James

Reputation: 18379

You could also create a new EntityManager and find the object, this would save detaching and merging the object.

If you are using EclipseLink you can unwrap the UnitOfWork form the EntityManager and call getCurrentChanges() to get a change set of changes made in the transaction. You could also use getOriginalVersionOfObject() to get the original object if using a shared cache.

EclipseLink also has full history support,

see, http://wiki.eclipse.org/EclipseLink/Examples/JPA/History

Upvotes: 3

Biju Kunjummen
Biju Kunjummen

Reputation: 49915

I have not used this personally, but heard good things about JBoss Envers , which is a auditing tool integrated with Hibernate. You may be able to use this for auditing what has changed for an entity, and exporting the specific changes.

Upvotes: 2

d1e
d1e

Reputation: 6442

If you use Hibernate, by default it uses first-level cache to cache repeatable queries which are made in the same session by default.

From Hibernate Recipes: A Problem-Solution Approach book:

The first-level cache is at the transaction level or the unit of work. It’s enabled by default in Hibernate. Caching at the first level is associated with a session. If the same query is executed multiple times in the same session, the data associated with the query is cached.

Suppose you retrieve an object more than once within a session: does Hibernate query the database as many times as the query is invoked?

Session session = factory.openSession();
try {
Book book1 = (Book) session.get(Book.class, id);
Book book2 = (Book) session.get(Book.class, id);
} finally {
session.close();
}

If you inspect the SQL statements executed by Hibernate, you find that only one database query is made. That means Hibernate is caching your objects in the same session. This kind of caching is called first-level caching, and its caching scope is a session.

Upvotes: 0

Related Questions