In the previous tutorial, I introduced to you all an overview of Jakarta Persistence Query Language to manipulate database types using entities. Whenever you need information from the database, you will use the SELECT or UPDATE, or DELETE statements and the entity name to build into the query, then retrieve the Query object from the Entity Manager using this query, and finally, call the appropriate method according to your needs from this query object to get the result you want. Many steps need to do, don’t you? If you use Jakarta Persistence with the Spring framework in your project then just try to use Spring Data JPA! It will help you minimize the work to be done in some cases. How is it in detail? In this tutorial, let’s learn about Spring Data JPA.
First, I will create a new Maven project as an example:

We will use Java 25 for this example:
|
1 2 3 4 |
<properties> <maven.compiler.source>25</maven.compiler.source> <maven.compiler.target>25</maven.compiler.target> </properties> |
Spring Data JPA dependency:
|
1 2 3 4 5 |
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>4.1.2</version> </dependency> |
Here, I will use JPA with the implementation of Hibernate so I will add Hibernate dependency as follows:
|
1 2 3 4 5 |
<dependency> <groupId>org.hibernate.orm</groupId> <artifactId>hibernate-core</artifactId> <version>7.4.14.Final</version> </dependency> |
Project Lombok:
|
1 2 3 4 5 6 |
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.48</version> <scope>provided</scope> </dependency> |
In this tutorial, I will use the MySQL database:
|
1 2 3 4 5 |
<dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>26.10.0</version> </dependency> |
For simplicity, I just defined a table containing student information with 2 columns as follows:
|
1 2 3 4 5 |
CREATE TABLE `student` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1; |
Sample data:

The entity of this table:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.huongdanjava.springdatajpa; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.Table; import lombok.Getter; import lombok.Setter; @Table(name = "students") @Entity @Getter @Setter public class Student { @Id @GeneratedValue private Long id; @Column private String name; } |
I will declare the EntityManagerFactory in the Spring container using the spring.xml:

as follows:
|
1 2 3 4 5 6 7 |
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="packagesToScan" value="com.huongdanjava.springdatajpa"/> <property name="dataSource" ref="dataSource"/> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/> </property> </bean> |
with datasource:
|
1 2 3 4 5 6 |
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3307/example" /> <property name="username" value="root" /> <property name="password" value="123456" /> </bean> |
OK, so we have just finished preparing. You can refer to the tutorial about Jakarta Persistence and the Spring framework here.
Now we go to the main topic of this tutorial.
First of all, you need to know that Spring Data JPA is a small module in a large project called the Spring Data project. The purpose of the Spring Data project is to minimize the repetitive code involved in accessing and manipulating data management systems when developing applications that use the Spring framework. In addition to Spring Data JPA support JPA for minimizing code to access and manipulate database management systems, we also have Spring Data JDBC (like Spring Data JPA), Spring Data LDAP (supports Spring LDAP), Spring Data MongoDB (support for MongoDB), etc. You can find all Spring Data modules here.
In order to achieve the purpose of minimizing code, Spring Data defines the main interface called Repository, which is part of the Spring Data Common module, and will be used for all the other modules in the Spring Data project. The content of this interface is as simple as:
|
1 2 3 4 5 6 7 8 |
package org.springframework.data.repository; import org.springframework.stereotype.Indexed; @Indexed public interface Repository<T, ID> { } |
This interface uses two generic types:
- T is the domain class that the repository will manage.
- ID is the data type of the ID of the domain class that the repository manages.
Because this interface is so simple, it must have other interfaces that extend it to represent what the Spring Data project does for you. 😀
Here, we will have more interfaces that extend from the Repository interface depending on the module we use, but since we are discussing the Spring Data JPA then I will only list here 2 interfaces that extend the Repository interface in which Spring Data JPA is in use. That’s the CrudRepository interface and PagingAndSortingRepository.
CrudRepository interface with the meaning of creating, reading, updating, and deleting allows us to perform basic operations on data systems (data systems here you have to understand in broad meaning that it is not just a database). The PagingAndSortingRepository interface supports pagination and sorting for Spring Data JPA. Both the CrudRepository and PagingAndSortingRepository interfaces have extensions to support List instead of Iterable: ListCrudRepository and ListPagingAndSortingRepository. All the interfaces mentioned above are in the Spring Data Common module.
The Spring Data JPA module defines an interface called JpaRepository that inherits from the ListCrudRepository, ListPagingAndSortingRepository, and QueryByExampleExecutor interfaces.
QueryByExampleExecutor is another interface from the Spring Data Common module. It provides additional functionality, allowing us to search for entities based on their non-null properties. I will discuss QueryByExampleExecutor in more detail in later articles!
By extending the ListCrudRepository and ListPagingAndSortingRepository interfaces, you can imagine how Spring Data JPA can help us minimize the code for database-related operations, right? These include: create, read, update, delete, paging, and sorting 😀
You can clearly see the extended structure for these interfaces in the following image:

Many query methods are supported by default by interfaces such as CrudRepository, PagingAndSortingRepository, ListCrudRepository, ListPagingAndSortingRepository, QueryByExampleExecutor, and JpaRepository. You just need to use them to interact with the database. Spring Data JPA will handle the tasks related to building and executing the query to retrieve the results.
OK, so let’s take an example with the JpaRepository interface to see how it works.
Now we will create an interface called StudentRepository extend from JpaRepository with the following content:
|
1 2 3 4 5 6 7 |
package com.huongdanjava.springdatajpa; import org.springframework.data.jpa.repository.JpaRepository; public interface StudentRepository extends JpaRepository<Student, Long> { } |
The domain class here is the Student entity and Long is the data type of the properties in the Student mapping entity with the primary key column in our students table.
Now we will declare this interface in the Spring container as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"> <jpa:repositories base-package="com.huongdanjava.springdatajpa"/> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="packagesToScan" value="com.huongdanjava.springdatajpa"/> <property name="dataSource" ref="dataSource"/> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/> </property> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3307/example"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> </beans> |
Here, I’m using the <jpa:repositories> tag with the base package com.huongdanjava.springdatajpa to scan the StudentRepository interface. With the above declaration, Spring Data JPA will automatically create a Repository Proxy object to retrieve the SimpleJpaRepository object that implements the StudentRepository interface, as you can see in the image above, to initialize it in the Spring container.
Since the object SimpleJpaRepository uses transactions, you need to declare the transactionManager bean in the Spring container.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <jpa:repositories base-package="com.huongdanjava.springdatajpa"/> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="packagesToScan" value="com.huongdanjava.springdatajpa"/> <property name="dataSource" ref="dataSource"/> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/> </property> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3307/example"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> <tx:annotation-driven proxy-target-class="true"/> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> </beans> |
Okay, we’ve completed the necessary configuration. Now let’s run an example. The main class to run our application is as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.huongdanjava.springdatajpa; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Application { static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml"); StudentRepository studentRepository = (StudentRepository) ac.getBean("studentRepository"); studentRepository.findById(1L).ifPresent(s -> System.out.println(s.getName())); } } |
The result will be:

Suppose, we now add a query method in the StudentRepository interface with the following contents:
|
1 2 3 4 5 6 7 8 |
package com.huongdanjava.springdatajpa; import org.springframework.data.jpa.repository.JpaRepository; public interface StudentRepository extends JpaRepository<Student, Long> { Student findByName(String name); } |
then when running the following example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.huongdanjava.springdatajpa; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Application { static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml"); StudentRepository studentRepository = (StudentRepository) ac.getBean("studentRepository"); Student student = studentRepository.findByName("Khanh Nguyen"); System.out.println(student.getId()); } } |
the result will be:

As you can see, even though there isn’t any class implementing the StudentRepository interface, we can still query the students table by column name. This significantly reduces the amount of code we need to write, doesn’t it?
