How can I use an EJB in a EntityListener?

微笑、不失礼 提交于 2020-06-16 17:38:06

问题


I'm designing my database and I reached the situation that an Entity itself requires to access database.

I read Why sometimes a reference to an EntityManager inside JPA entities is needed.

And I'm curious about the possibility of accessing an EJB in EntityListener.

public class MyEntityListener {

    @PrePersist
    private void onPrePersist(final Object object) {
        // find an EJB
        // and set those required values
        // which each resides in a specific table.
    }
}

Is this possible or (or and) preferred?


回答1:


I found an answer.

  • CDI injection in EntityListeners
  • https://blogs.oracle.com/arungupta/entry/jpa_2_1_early_draft

It seems possible, according to JSR 338: JavaTM Persistence 2.1.

3.5.1 Entity Listeners

Entity listener classes in Java EE environments support dependency injection through the Contexts and Dependency Injection API (CDI) [ 10 ] when CDI is enabled[43]. An entity listener class that makes use of CDI injection may also define lifecycle callback methods annotated with the PostConstruct and PreDestroy annotations. These methods will be invoked after injection has taken place and before the entity listener instance is destroyed respectively.

The persistence provider is responsible for using the CDI SPI to create instances of the entity listener class; to perform injection upon such instances; to invoke their PostConstruct and PreDestroy methods, if any; and to dispose of the entity listener instances.



来源:https://stackoverflow.com/questions/38582007/how-can-i-use-an-ejb-in-a-entitylistener

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