Reputation: 47
I can set default entity listener use persistence.xml
.
How to set default entity listener use java code in spring-data-jpa
?
I want to set the entity listener dynamically, hibernate.session_factory.interceptor
I did not find this in the hibernate or spring-data-jpa documentation.
<entity-mappings xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm
http://xmlns.jcp.org/xml/ns/persistence/orm_2_1.xsd"
version="2.1">
<persistence-unit-metadata>
<persistence-unit-defaults>
<entity-listeners>
<entity-listener
class="com.miya.system.listener.BackupDataListener">
<post-remove method-name="postRemove" />
</entity-listener>
</entity-listeners>
</persistence-unit-defaults>
</persistence-unit-metadata>
</entity-mappings>
Upvotes: 1
Views: 932
Reputation: 10716
You can customize the definition of LocalContainerEntityManagerFactoryBean
to point it to your custom persistence.xml
. The quick and dirty way in Spring Boot would be to create a BeanPostProcessor
:
@Component
public class PersistenceXmlPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
if (bean instanceof LocalContainerEntityManagerFactoryBean && runtimeConditionMet()) {
((LocalContainerEntityManagerFactoryBean) bean).setPersistenceXmlLocation(<your custom persistence.xml location>)
}
return bean;
}
}
As an alternative, you could customize the entity manager factory using BaseJpaAutoConfiguration
:
@SpringBootApplication(exclude = HibernateJpaAutoConfiguration.class)
public class MyApplication {
...
}
@Configuration
public class CustomHibernateJpaConfiguration extends JpaBaseConfiguration {
...// copy most methods over from HibernateJpaConfiguration
@Override
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder factoryBuilder) {
var result = super.entityManagerFactory(factoryBuilder);
result.setPersistenceXmlLocation(...);
return result;
}
}
(an even cleaner solution could be to extend EntityManagerFactoryBuilder
, but I hope you get the general idea).
Upvotes: 1