Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Proare33% off untilnextMonday:

>>EXPLORE ACCESS NOW

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a14-Day FreeTrial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a14-DayFree Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with SpringCloud:

>> Join Pro and download theeBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockitolibrary makes it easy to writeclean and intuitive unittests for your Java code.

Get started with mocking and improve your application testsusing ourMockito guide:

Download theeBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the SpringWebFlux module, which has been improved upon ever since. Getstarted with the Reactor project basics andreactive programmingin Spring Boot:

>> Join Pro anddownload the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become astaple of Java development. The basic operations like iterating,filtering, mapping sequences of elements are deceptively simple touse.

But these can also be overused and fall into some commonpitfalls.

Toget a better understanding on how Streams work and howto combine them with other language features, check out our guideto Java Streams:

>> Join Proand download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download theE-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download theE-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download theE-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore theeBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through theLearnSpring course:

>> LEARNSPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building afullREST API with the framework:

>>The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advancedfunctionality within the Core to the deep OAuth support in theframework.

I built the security material astwo full courses - Core andOAuth, to get practical with these more complex scenarios. Weexplore when and how to use each feature andcode through it onthe backing project.

You can explore the course here:

>> Learn SpringSecurity

Partner – Orkes – NPI EA (cat=Java)
announcement - icon

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a14-DayFree Trial of Orkes Conductor today.

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle thecomplexity ofJPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided referencecourse:

>> CHECK OUT THECOURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — withOpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy toput off. That’s where OpenRewrite comes in. The open-sourceframework for large-scale, automated code transformations helpsteams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite atModerne run live, hands-on training sessions — one for newcomersand one for experienced users. You’ll see how recipes work, how toapply them across projects, and how to modernize code withconfidence.

Join the next session,bring your questions, and learn how to automate the kind of workthat usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the releaseprocess, to ensure that new code doesn't break the existingfunctionality. As the codebase evolves, we want to run these testsfrequently to help catch any issues early on.

The best way to ensure these tests run frequently on anautomated basis is, of course,to include them in the CI/CDpipeline. This way, the regression tests will executeautomatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests usingSelenium, and then include them in our pipelineusing GitHubActions:, to berun on the LambdaTest cloud grid:

>> How to Run SeleniumRegression Tests With GitHub Actions

Course – Black Friday 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Proare33% off untilnextMonday:

>> EXPLOREACCESS NOW

1. Overview

This tutorial will focus onintroducing Spring Data JPA into a Spring project, and fully configuring the persistence layer. For a step-by-step introduction to setting up the Spring context using Java-based configuration and the basic Maven pom for the project, seethis article.

Further reading:

A Guide to JPA with Spring

Setup JPA with Spring - how to set up the EntityManager factory and use the raw JPA APIs.

CrudRepository, JpaRepository, and PagingAndSortingRepository in Spring Data

Learn about the different flavours of repositories offered by Spring Data.

Simplify the DAO with Spring and Java Generics

Simplify the Data Access Layer by using a single, generified DAO, which will result in <strong>elegant data access</strong>, no unnecessary clutter.

2. The Spring Data Generated DAO – No More DAO Implementations

As we discussed in an earlier article,the DAO layer usually consists of a lot of boilerplate code that can and should be simplified. The advantages of such a simplification are many: a decrease in the number of artifacts that we need to define and maintain, consistency of data access patterns, and consistency of configuration.

Spring Data takes this simplification one step further andmakes it possible to remove the DAO implementations entirely. The interface of the DAO is now the only artifact that we need to explicitly define.

To start leveraging the Spring Data programming model with JPA, a DAO interface needs to extend the JPA specificRepository interface,JpaRepository. This will enable Spring Data to find this interface and automatically create an implementation for it.

By extending the interface, we get the most relevant CRUD methods for standard data access available in a standard DAO.

3. Custom Access Method and Queries

As discussed,by implementing one of theRepository interfaces, the DAO will already have some basic CRUD methods (and queries) defined and implemented.

To define more specific access methods, Spring JPA supports quite a few options:

  • simply define a new method in the interface
  • provide the actualJPQL query by using the@Query annotation
  • use the more advancedSpecification and Querydsl support in Spring Data
  • definecustom queries via JPA Named Queries

Thethird option, Specifications, and Querydsl support, is similar to JPA Criteria but uses a more flexible and convenient API. This makes the whole operation much more readable and reusable. The advantages of this API will become more pronounced when dealing with a large number of fixed queries, as we could potentially express these more concisely through a smaller number of reusable blocks.

The last option has the disadvantage that it either involves XML or burdening the domain class with the queries.

3.1. Automatic Custom Queries

When Spring Data creates a newRepository implementation, it analyses all the methods defined by the interfaces and tries toautomatically generate queries from the method names. While this has some limitations, it’s a very powerful and elegant way of defining new custom access methods with very little effort.

Let’s look at an example. If the entity has anamefield (and the Java Bean standardgetName andsetName methods),we’ll define thefindByName method in the DAO interface. This will automatically generate the correct query:

public interface IFooDAO extends JpaRepository<Foo, Long> {    Foo findByName(String name);}

This is a relatively simple example. The query creation mechanism supportsa much larger set of keywords.

In case the parser can’t match the property with the domain object field, we’ll see the following exception:

java.lang.IllegalArgumentException: No property nam found for type class com.baeldung.jpa.simple.model.Foo

3.2. Manual Custom Queries

Now let’s look at a custom query that we’ll define via the@Query annotation:

@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")Foo retrieveByName(@Param("name") String name);

For even more fine-grained control over the creation of queries, such as using named parameters or modifying existing queries,the reference is a good place to start.

4. Transaction Configuration

The actual implementation of the Spring-managed DAO is indeed hidden since we don’t work with it directly. However, it’s a simple enough implementation,theSimpleJpaRepository, which defines transaction semantics using annotations.

More explicitly, this uses a read-only@Transactional annotation at the class level, which is then overridden for the non-read-only methods. The rest of the transaction semantics are default, but these can be easily overridden manually per method.

4.1. Exception Translation Is Alive and Well

The question now becomes: since Spring Data JPA doesn’t depend on the old ORM templates (JpaTemplate,HibernateTemplate), and they have been removed since Spring 5, are we still going to get our JPA exceptions translated to Spring’sDataAccessException hierarchy?

The answer is, of course, we are.Exception translation is still enabled by the use of the@Repository annotation on the DAO. This annotation enables a Spring bean postprocessor to advise all@Repository beans with all thePersistenceExceptionTranslator instances found in the container and provide exception translation just as before.

Let’s verify exception translation with an integration test:

@Test(expected = DataIntegrityViolationException.class)public void whenInvalidEntityIsCreated_thenDataException() {    service.create(new Foo());}

Keep in mind thatexception translation is done through proxies. For Spring to be able to create proxies around the DAO classes, these must not be declaredfinal.

5. Spring Data JPA Repository Configuration

To activate the Spring JPA repository support, we can use the@EnableJpaRepositories annotation and specify the package that contains the DAO interfaces:

@EnableJpaRepositories(basePackages = "com.baeldung.jpa.simple.repository") public class PersistenceConfig {     ...}

We can do the same with an XML configuration:

<jpa:repositories base-package="com.baeldung.jpa.simple.repository" />

6. Java or XML Configuration

We already discussed in great detail how toconfigure JPA in Spring in a previous article. Spring Data also takes advantage of Spring’s support for the JPA@PersistenceContext annotation. It uses this to wire theEntityManager into the Spring factory bean responsible for creating the actual DAO implementations,JpaRepositoryFactoryBean.

In addition to the already discussed configuration, we also need to include the Spring Data XML Config if we are using XML:

@Configuration@EnableTransactionManagement@ImportResource("classpath*:*springDataConfig.xml")public class PersistenceJPAConfig {    ...}

7. Maven Dependency

In addition to the Maven configuration for JPA, like in aprevious article, we’ll addthespring-data-jpa dependency:

<dependency>    <groupId>org.springframework.data</groupId>    <artifactId>spring-data-jpa</artifactId><version>3.5.7</version></dependency>

8. Using Spring Boot

We can also use theSpring Boot Starter Data JPA dependency that will automatically configure theDataSource for us.

We need to make sure that the database we want to use is present in the classpath. In our example, we’ve added the H2 in-memory database:

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-data-jpa</artifactId><version>3.5.7</version></dependency><dependency>    <groupId>com.h2database</groupId>    <artifactId>h2</artifactId></dependency>

As a result, just by doing these dependencies, our application is up and running and we can use it for other database operations.

The explicit configuration for a standard Spring application is now included as part of Spring Boot auto-configuration.

We can, of course, modify the auto-configuration by adding our customized explicit configuration.

Spring Boot provides an easy way to do this using properties in theapplication.properties file. Let’s see an example of changing the connection URL and credentials:

spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1spring.datasource.username=saspring.datasource.password=sa

9. Useful Tools for Spring Data JPA

Spring Data JPA is supported in all major Java IDEs. Let’s see what useful tools are available for Eclipse and IntelliJ IDEA.

If you use Eclipse as your IDE, you can install theDali Java Persistence Tools plugin. This provides ER diagrams for JPA entities, DDL generation to initialize schema and basic reverse engineering capabilities. Also, you can use Eclipse Spring Tool Suite (STS). It will help to validate query method names in Spring Data JPA repositories.

In case you use IntelliJ IDEA, there are two options.

IntelliJ IDEA Ultimate enables ER diagrams, a JPA console for testing JPQL statements, and valuable inspections. However, these features are not available in the Community Edition.

To boost productivity in IntelliJ, you can install theJPA Buddy plugin, which provides many features, including generation of JPA entities, Spring Data JPA repositories, DTOs, initialization DDL scripts, Flyway versioned migrations, Liquibase changelogs, etc. Also, JPA Buddy provides an advanced tool for reverse engineering.

Finally, the JPA Buddy plugin works with both Community and Ultimate editions.

10. Conclusion

In this article, we covered the configuration and implementation of the persistence layer with Spring 5, JPA 2, and Spring Data JPA (part of the Spring Data umbrella project) using both XML and Java-based configuration.

We discussed ways to define moreadvanced custom queries, as well astransactional semantics, and aconfiguration with the newjpa namespace. The final result is a new and elegant take on data access with Spring, with almost no actual implementation work.

The code backing this article is available on GitHub. Once you'relogged in as aBaeldung Pro Member, start learning and coding on the project.
Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Proare33% off untilnextMonday:

>>EXPLORE ACCESS NOW

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a14-Day FreeTrial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a14-DayFree Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

TheApache HTTP Client is a very robust library, suitablefor both simple and advanced use cases whentesting HTTPendpoints. Check out our guide covering basic request andresponse handling, as well as security, cookies, timeouts, andmore:

>> Downloadthe eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky processwith manypotential pitfalls. A solid grasp of thefundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications withourJava Concurrency guide:

>>Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become astaple of Java development. The basic operations like iterating,filtering, mapping sequences of elements are deceptively simple touse.

But these can also be overused and fall into some commonpitfalls.

Toget a better understanding on how Streams work and howto combine them with other language features, check out our guideto Java Streams:

>> Join Proand download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring,through theLearn Spring course:

>> CHECK OUTTHE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebasesdon’t always keep up. Frameworks change, dependencies drift, andtech debt builds until it starts to drag on delivery. OpenRewritewas built to fix that: an open-source refactoring engine thatautomates repetitive code changes while keeping developer intentintact.

The monthly training series, led by the creators and maintainersof OpenRewrite at Moderne, walks through real-world migrations andmodernization patterns. Whether you’re new to recipes or ready towrite your own, you’ll learn practical ways to refactor safely andat scale.

If you’ve ever wished refactoring felt as natural — and as fast— as writing code,this is a goodplace to start.

Course – Black Friday 2025 – NPI (All)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Proare33% off untilnextMonday:

>> EXPLOREACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)
Do JSON right with Jackson - book cover
Do JSON right with Jackson - icon
Do JSON right with Jackson
Download the E-book