How to insert an EntityManager into a Hibernate Bean interceptor using Spring?

I need to create a Hibernate interceptor that must have access to the entity manager. The problem is that when I determine how an EntityManagerFactory will be created using Spring's XML configuration file to define the entityManagerFactory bean, I have to say that the entity controls the bean interceptor that it should use. The fact is that my Interceptor bean has a control field for the entered entity defined using

@PersistenceContext private EntityManager entityManager; 

When I do this, Spring throws the following exception:

Called: org.springframework.beans.factory.BeanCreationException: Error creating bean named 'ar.com.zauber.commons.repository.utils.ConfigurableHibernatePersistence # 50d17ec3' defined in the class path resource [ar / com / xxx / impl / config / persistence / persistence-impl-xxx-spring.xml]: Cannot resolve the reference to the 'interceptor' bean when setting the bean properties interceptor; The nested exception is org.springframework.beans.factory.BeanCreationException: error creating bean named "interceptor": injection persistence dependency injection failed; The nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean named "entityManagerFactory": FactoryBean, which is currently being created, returns null from getObject

The problem is that entity manager cannot be entered because the factory entity manager is being created.

Any idea how I can solve this problem?

+4
source share
1 answer

Use depends on (XML version):

 <bean id="interceptor" class="YourHibernateInterceptor" depends-on="entityManagerFactory"/> 

Or @DependsOn (annotation version):

 @DependsOn("entityManagerFactory") public class YourHibernateInterceptor{ // ... } 

Reference:


If this does not work because the chicken / egg problem (EntityManagerFactory depends on SessionFactory, SessionListener depends on EntityManagerFactory, you can mark your SessionListener as ApplicationContextAware or ApplicationListener<ContextRefreshedEvent> and manually connect EntityManager :

 this.entityManager = context.getBean(EntityManager.class); 
+3
source

Source: https://habr.com/ru/post/1342547/


All Articles