开发者

How to implement history table with pure JPA?

开发者 https://www.devze.com 2023-02-28 15:01 出处:网络
I need to keep change of one \"entity_name\" into another log table called \"entity_name_history\" without using any JPA provider (I have to change existing project which doesn\'t use one). What I wan

I need to keep change of one "entity_name" into another log table called "entity_name_history" without using any JPA provider (I have to change existing project which doesn't use one). What I want to know is there anyway to implement history in pure JPA.

I have bee开发者_运维技巧n looking into some persistent event intercept like @postUpdate, but from what I know I can't use entitymanager in those callback, if it can please tell me.


The easiest and most clean solution is using database triggers to implement history feature.


There is an abundant litterature about that subject, although it's usually called "entity auditing". Hibernate provides a module, called Hibernate Envers, specially built for that, and obviously using that kind of JPA triggers.

There is also a (good?) tutorial on implementing it using TopLink (now EclipseLink).

So, yes, that's the way to do, but, no, you shouldn't do it by yourself.


I think it can be used, just it has to be used with care. Here is quote from JPA specification:

In general, portable applications should not invoke EntityManager or Query operations, access other entity instances, or modify relationships in a lifecycle callback method.

As an alternative you can use different entity manager or use pure JDBC data source connection that will live in the same transaction. Especially, if you don't need to do any manipulations with your history objects in the same JPA session.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号