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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Less Code With Spring Data Rest
  • Calling Stored Procedures With IN and OUT Parameters From Spring Data JPA
  • Spring Data: Easy MongoDB Migration Using Mongock

Trending

  • Securing the Future: Best Practices for Privacy and Data Governance in LLMOps
  • Modern Test Automation With AI (LLM) and Playwright MCP
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  • Start Coding With Google Cloud Workstations
  1. DZone
  2. Data Engineering
  3. Data
  4. Accessing the EntityManager From Spring Data JPA

Accessing the EntityManager From Spring Data JPA

Learn how to access your EntityManager using a custom interface with Spring Data JPA as well as the benefits and drawbacks involved.

By 
Martin Farrell user avatar
Martin Farrell
·
Nov. 09, 17 · Tutorial
Likes (16)
Comment
Save
Tweet
Share
194.6K Views

Join the DZone community and get the full member experience.

Join For Free

Spring Data JPA allows you to rapidly develop your data access layer through the use of Repository interfaces. Occasionally, you will need to access the EntityManager from Spring Data JPA. This post shows you how to access the EntityManager.

EntityManager

The purpose of the EntityManager is to interact with the persistence context. The persistence context will then manage entity instances and their associated lifecycle. This was covered in my blog post on the JPA Entity Lifecycle.

Spring Data JPA does an excellent job abstracting you from the EntityManager through its Repository interfaces:

  • Repository
  • CrudRepository
  • JPARepository

But occasionally, you need to access the EntityManager.

EntityManager.refresh

An example of this is the refresh method. The refresh method refreshes the state of an instance from the database and overwrites the copy held by the EntityManager. This ensures the EntityManager manager has the most up to date version of the data

Spring Data JPA Example

Let's use the JPA object from my normal test ground:

@Entity
@Table(name = "PARKRUNCOURSE")
public class ParkrunCourse {
    @Id
    @Column(name = "PRCOURSE_ID")
    @GeneratedValue
    private Long courseId;
    @Column(name = "COURSENAME")
    private String courseName;
    @Column(name = "URL")
    private String url;
    @Column(name = "AVERAGETIME")
    private Long averageTime;
}


And it's associated repository:

public interface ParkrunCourseRepository extends CrudRepository {
}


This is a standard implementation of a Spring repository, with the CrudRepository taking ParkrunCourse, and its key type Long

Create Custom Interfaces and Implementation

The first step is to define a new interface with the same signature as the underlying EntityManager method we want to access:

public interface ParkrunCourseRepositoryCustom {
    void refresh(ParkrunCourse parkrunCourse);
}


The key point is the custom implementation must end with “Custom” — unless overridden in Spring Data configuration.

Next, we provide the implementation for this interface and inject the EntityManager:

import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import com.glenware.springboot.form.ParkrunCourse;
import org.springframework.transaction.annotation.Transactional;
public class ParkrunCourseRepositoryImpl implements ParkrunCourseRepositoryCustom {
    @PersistenceContext
    private EntityManager em;
    @Override
    @Transactional
    public void refresh(ParkrunCourse parkrunCourse) {
        em.refresh(parkrunCourse);
    }
}


We must end our implementation name with “Impl”.

We then change the ParkrunCourseRepository interface to:

public interface ParkrunCourseRepository extends CrudRepository, ParkrunCourseRepositoryCustom {
}


We can then refresh our JPA object:

@Autowired
private ParkrunCourseRepository parkrunCourseRepository;
ParkrunCourse parkrunCourse = parkrunCourseRepository.findOne(1L);
// Do some work & in the mean time the database has been updated by a batch job
// refresh object and now up to date
parkrunCourseRepository.refresh(parkrunCourse);


Conclusions

This approach shows how to access the EntityManager using Spring Data JPA. The advantage of this approach is you can access the EntityManager for a specific JPA implementation. The disadvantage of this approach is that you would need to repeat this task for each JPA implementation. The next post looks at a more generic approach to the custom repository implementation, allowing other JPA objects to benefit.

Spring Data Data (computing) Spring Framework

Published at DZone with permission of Martin Farrell, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Less Code With Spring Data Rest
  • Calling Stored Procedures With IN and OUT Parameters From Spring Data JPA
  • Spring Data: Easy MongoDB Migration Using Mongock

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • 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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!