简体   繁体   中英

How to set default entity listener use java code in `spring-data-jpa`?

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.

hibernate docs

<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>

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM