Anyways, I got this done by getting entityManager reference from EntityManagerFactory
bean which is configured in my jdbc-config.xml
. But again this is not what I wanted. I wanted to work around with @PersistenceContext
.
@Autowired
EntityManagerFactory entityManagerFactory;
private static EntityManager entityManager;
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
entityManager=entityManagerFactory.createEntityManager();
this.entityManagerFactory = entityManagerFactory;
}
Here are few notes that we need to keep in mind:
- We can't inject an
EntityManager
into anEntityListener
(through@PersistenceContext
).EntityListener
is not managed by any of the containers @PersistenceContext
class cannot be static. So we cant attain the instance while class loading.- EntityListeners are
instantiated by JPA, so Spring does not have an opportunity to
inject
EntityManager