Social Media

Category Archives for Java8

Photo by Dario Gartmann on Unsplash

Add EntityManager.refresh to all Spring Data Repositories

In my previous post Access the EntityManager from Spring Data JPA I showed how to extend a single Spring Data JPA repository to access the EntityManager.refresh method. This post demonstrates how to Add EntityManager.refresh to all Spring Data Repositories.

Source Code

The first step is to define your interface –

The key points are –

  • @NoRepositoryBean – This prevents an instance of a Repository being created
  • Extending the CrudRepository – You need to decided which Repository to extend. Im using CrudRepository as this was used in the previous post
  • void refresh method signature is the same as the EntityManager.refresh method

Implementation

The next step is to implement this interface in a custom repository –

Key points are –

  • Extend SimpleJpaRepository repository. The SimpleJpaRepository is the default implementation for CrudRepository
  • Constructor is the SimpleJpaRepository constructor taking the JpaEntityInformation and EntityManager objects.
  • We save a local copy of the EntityManager
  • refresh method simply calls the EntityManager.refresh method

The final step is to let Spring Data know that its base class is CustomRepositoryImpl –

Key Points –

  • EnableJpaRepositories -This annotation enables JPA repositories, and will scan com.glenware.springboot by default
  • repositoryBaseClass attribute is used to let the Spring Data configuration know we are overriding the default base class

All Together Now

We can then use this repository in our classes so we change our repository from the previous post from CrudRepository to extend CustomRepository –

We can now access the EntityManager.refresh method using –

The above code was tested by running it against Spring Boot (1.5.6-Release) which used Spring Data JPA 1.11.6.Release. I can add the code to github if requested

Gotcha’s

One area you need to check is what version of Spring Data JPA you are running for extending repositories. I’ve had to adapt this approach for older repositories, although this is the current method using Spring Data JPA 1.11.6 Release

1 2 3 9