DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Auditing Spring Boot Using JPA, Hibernate, and Spring Data JPA
  • Marco Codes Live: Gavin King and Hibernate 6.3 [Video]
  • Postgres JSON Functions With Hibernate 6
  • Hibernate Get vs. Load

Trending

  • REST vs. Message Brokers: Choosing the Right Communication
  • Software Verification and Validation With Simple Examples
  • Build a Serverless App Fast With Zipper: Write TypeScript, Offload Everything Else
  • The Convergence of Testing and Observability
  1. DZone
  2. Coding
  3. Java
  4. Spring-managed Hibernate Listeners with JPA

Spring-managed Hibernate Listeners with JPA

Bozhidar Bozhanov user avatar by
Bozhidar Bozhanov
·
Oct. 01, 11 · Interview
Like (0)
Save
Tweet
Share
18.12K Views

Join the DZone community and get the full member experience.

Join For Free

A standard use-case – you need an entity listener in order to execute some code on every update/insert/delete. For auditing, for example. But things are not straightforward if you need spring dependencies in your listeners and you are using JPA.

First of all, the JPA-only listeners are insufficient – you can annotate a method with @PreUpdate, but the most you can get as context is the entity it is about (documentation). But you may need the old values. Or the extracted ID of the entity. Or other metadata. All of that is not supported by JPA. So you need to implement hibernate interfaces like PreDeleteEventListener, PreUpdateEventListener, PostInsertEventListener, etc. and get their XEvent objects.

But you can’t easily have these listeners both spring-managed and registered if you are using JPA. You can list them as class names in some hibernate-specific property in persistence.xml, but that way hibernate will instantiate them. Below is the tweaks you need to make in order to get this working:

First, extend the persistence provider:

public class HibernateExtendedPersistenceProvider extends HibernatePersistence {

    private PostInsertEventListener[] postInsertEventListeners;
    private PreUpdateEventListener[] preUpdateEventListeners;
    private PreDeleteEventListener[] preDeleteEventListeners;

    @SuppressWarnings("rawtypes")
    @Override
    public EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) {
        Ejb3Configuration cfg = new Ejb3Configuration();
        setupConfiguration(cfg);
        Ejb3Configuration configured = cfg.configure( persistenceUnitName, properties );
        return configured != null ? configured.buildEntityManagerFactory() : null;
    }

    @SuppressWarnings("rawtypes")
    @Override
    public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) {
        Ejb3Configuration cfg = new Ejb3Configuration();
        setupConfiguration(cfg);
        Ejb3Configuration configured = cfg.configure( info, properties );
        return configured != null ? configured.buildEntityManagerFactory() : null;
    }

    private void setupConfiguration(Ejb3Configuration cfg) {
        cfg.getEventListeners().setPostInsertEventListeners(postInsertEventListeners);
        cfg.getEventListeners().setPreDeleteEventListeners(preDeleteEventListeners);
        cfg.getEventListeners().setPreUpdateEventListeners(preUpdateEventListeners);
        //TODO if others are needed - add them
    }

    public void setPostInsertEventListeners(PostInsertEventListener[] postInsertEventListeners) {
        this.postInsertEventListeners = postInsertEventListeners;
    }

    public void setPreUpdateEventListeners(PreUpdateEventListener[] preUpdateEventListeners) {
        this.preUpdateEventListeners = preUpdateEventListeners;
    }

    public void setPreDeleteEventListeners(PreDeleteEventListener[] preDeleteEventListeners) {
        this.preDeleteEventListeners = preDeleteEventListeners;
    }
}

Then annotate your listener(s) with @Component (or declare them as spring beans the way you prefer). Then register them:

<bean id="hibernatePersistenceProvider" class="com.foo.bar.configuration.HibernateExtendedPersistenceProvider">
<property name="postInsertEventListeners">
<list>
<ref bean="hibernateAuditLogListener" />
</list>
</property>
<property name="preUpdateEventListeners">
<list>
<ref bean="hibernateAuditLogListener" />
</list>
</property>
<property name="preDeleteEventListeners">
<list>
<ref bean="hibernateAuditLogListener" />
</list>
</property>
</bean>

And finally, set the customized persistence provider to the entity manager factory bean:

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceProvider" ref="hibernatePersistenceProvider" />

What you just did:

  • Made use of the fact that the PersistenceProvider allows you to obtain the hibernate Configuration object, which is not otherwise accessible when working with JPA
  • Registered your listeners as spring beans and added them to the extended persistence provider, which in turn registers them with hibernate
  • set the “persistenceProvider” property of spring’s LocalContainerEntityManagerFactoryBean. Normally you don’t set that, because it is inferred from the vendor adapter or from the classpath.

 

From http://techblog.bozho.net/?p=600

Hibernate

Opinions expressed by DZone contributors are their own.

Related

  • Auditing Spring Boot Using JPA, Hibernate, and Spring Data JPA
  • Marco Codes Live: Gavin King and Hibernate 6.3 [Video]
  • Postgres JSON Functions With Hibernate 6
  • Hibernate Get vs. Load

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: