How to inject EntityManager in EntityListeners

后端 未结 4 1273
死守一世寂寞
死守一世寂寞 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:09

    Well, the first solution which came into my mind is a little "hack", but should work.

        public class AuditInterceptor {
    
            static setEntityManager emf; 
    
            @Autowired
            public void setEntityManagerFactory(EntityManager emf) {
                AuditInterceptor.emf = emf;
            }
    
            @PrePersist
            public void prePersist(Object obj) { 
                EntityManager entityManager = emf.getEntityManager();
                // Here I want to use ENTITY manager object so that I can perform CRUD operation
                // with prePersist coming object.
    
                entityManager.unwrap(Session.class).save(obj);
    
                // But I am getting NULL POINTER EXCEPTION for entity manager object 
           }
       }
    

    Inside of your code use EntityManager entityManager = emf.getEntityManager()

    Declare your AuditInterceptor as a spring bean (@Component with component-scan or define AuditorInterceptor as a bean)

提交回复
热议问题