Correct way to do an EntityManager query during Hibernate Validation

后端 未结 3 1142
一个人的身影
一个人的身影 2021-01-02 14:04

I\'m a bit of a Java EE/EJB noob, but from the docs and other posts I\'ve gathered you cannot query the database using the same entitymanager/session during entity validatio

3条回答
  •  孤城傲影
    2021-01-02 14:20

    Translation please?

    The lifecycle events should not use the entity manager since it could lead to regressions. Imagine that during a pre-update event, you modify another entity. This should generate another pre-update event within the previous pre-update event. To avoid such issues, the use of entity manager is discouraged.

    But if all you want to do is read some additional data, conceptually there is not problem. Valation happens implicitly in pre-update and pre-insert events.

    If you never use post-load events, then reading data in a lifecycle event shouldn't trigger nested lifecycle events. As far as I understand the spec, querying entities is not stricly forbidden but strongly discouraged. In this case it might be fine. Did you try if this works?

    So what's the general pattern for getting at an EntityManagerFactory from a Validator?

    Injection works only in managed entities. When injection is not possible, you should be able to do a good old lookup to obtain an entity manager. When using the second entity manager, nested lifecycle events might be generated, though. But if you only do something trivial like reading a list of old password, that should be OK.

提交回复
热议问题