如何在EntityListeners中注入EntityManager
我需要在EntityListener类中注入EntityManager,以便可以对其执行CRUD操作。
POJO:
@Entity@EntityListner(AuditLogging.class)
class User
{
//Getter / setter of properties
}
AuditLogging(侦听器类)
public class AuditInterceptor{
@PersistenceContext
EntityManager entityManager;
public void setEntityManager(EntityManager entityManager)
{
this.entityManager = entityManager;
}
@PrePersist
public void prePersist(Object obj)
{
// 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
}
}
JDBC-CONFIg.xml
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
<property name="packagesToScan" value="com.XXXXX.entity" />
<property name="jpaProperties">
</bean>
<!-- Datasource -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driver.classname}" />
<property name="jdbcUrl" value="${jdbc.url}" />
</bean>
<!-- transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
EntityListener不受任何容器的管理。EntityListeners由JPA实例化,因此Spring没有机会注入EntityManager。我的问题是,我们如何在EntityListener类中注入EntityManager,以便可以对其执行CRUD操作?
回答:
无论如何,我是通过从EntityManagerFactory
配置在bean中的bean 获取entityManager引用来完成此操作的jdbc-
config.xml。但这又不是我想要的。我想和一起工作@PersistenceContext
。
@Autowired EntityManagerFactory entityManagerFactory;
private static EntityManager entityManager;
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
entityManager=entityManagerFactory.createEntityManager();
this.entityManagerFactory = entityManagerFactory;
}
以下是我们需要记住的一些注意事项:
- 我们无法将插入
EntityManager
到EntityListener
(通过@PersistenceContext
)。EntityListener
不受任何容器管理 @PersistenceContext
类不能是静态的。所以我们不能在类加载时获得实例。- EntityListeners由JPA实例化,因此Spring没有机会注入
EntityManager
以上是 如何在EntityListeners中注入EntityManager 的全部内容, 来源链接: utcz.com/qa/423263.html