How to use EntityManager from @PrePersist?

不羁的心 提交于 2019-12-06 05:47:34

Unfortunately, there is no clean, portable way to what you propose. The JPA 2 specification (JSR 317) states the following:

In general, the lifecycle method of a portable application should not invoke EntityManager or Query operations, access other entity instances, or modify relationships within the same persistence context.

As far as implementations go, Hibernate forbids it explicitly:

A callback method must not invoke EntityManager or Query methods!

I know it's not really what you were hoping for, but it seems that you will have to allocate the revision management responsibility to the clients of your entity class.

This might be a good place for the transfer object pattern. We normally do it like this:
1. convert the post entity to a post transfer object
2. once the post is saved we'd select the highest revisionId, increment it and create a new entity

Alternatively, you could update the current post and add an entry to a history table (possible even in a separate database). Thus you could keep the post table as small as possible for better performance since most of the time the current version of a post would be required anyway.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!