问题
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
andPreDestroy
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
andPreDestroy
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