How to inject EntityManager in EntityListeners

后端 未结 4 1268
死守一世寂寞
死守一世寂寞 2020-12-06 13:32

I need to inject EntityManager in EntityListener class so that I can perform CRUD operation on it.

POJO:

@Entity
@EntityListner(AuditLogging.class)
c         


        
4条回答
  •  时光取名叫无心
    2020-12-06 14:16

    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:

    1. We can't inject an EntityManager into an EntityListener (through @PersistenceContext). EntityListener is not managed by any of the containers
    2. @PersistenceContext class cannot be static. So we cant attain the instance while class loading.
    3. EntityListeners are instantiated by JPA, so Spring does not have an opportunity to inject EntityManager

提交回复
热议问题