Spring Data JPA Tutorial for Beginners with Examples

Spring Data JPA Tutorial for Beginners with Examples

Spring Data JPA Tutorial for Beginners with Examples

Introduction

Spring Data JPA is one of the most powerful modules in the Spring ecosystem. It simplifies database operations by reducing boilerplate code and providing built-in implementations for common CRUD operations.

Before Spring Data JPA, developers had to write large amounts of JDBC and Hibernate code to interact with databases. With Spring Data JPA, most database operations can be performed using simple repository interfaces.

In this tutorial, you'll learn how Spring Data JPA works, how to create repositories, perform CRUD operations, use query methods, implement pagination, and write custom queries.


What is Spring Data JPA?

Spring Data JPA is a Spring framework module that simplifies data access using JPA (Java Persistence API).

It provides:

  • Repository abstraction
  • Automatic CRUD operations
  • Query method generation
  • Pagination support
  • Sorting support
  • Custom query support

Instead of writing SQL for common operations, developers can use repository interfaces and let Spring generate the implementation automatically.


How Spring Data JPA Works

Controller
    ↓
Service
    ↓
Repository
    ↓
Spring Data JPA
    ↓
Hibernate
    ↓
MySQL Database

Explanation

  • Controller receives requests
  • Service processes business logic
  • Repository handles database access
  • Spring Data JPA generates queries
  • Hibernate translates operations into SQL
  • MySQL stores and retrieves data

JPA vs Hibernate vs Spring Data JPA

Many beginners get confused by these technologies.

TechnologyPurpose
JPASpecification
HibernateJPA Implementation
Spring Data JPASimplifies JPA Usage

Example

JPA defines rules.

Hibernate implements those rules.

Spring Data JPA makes Hibernate easier to use.


Maven Dependencies

Add the following dependencies to your pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
</dependency>

Configure Database Connection

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/employee_db

spring.datasource.username=root

spring.datasource.password=password

spring.jpa.hibernate.ddl-auto=update

spring.jpa.show-sql=true

Create Entity Class

Employee.java

@Entity
@Table(name = "employees")
public class Employee {

    @Id
    @GeneratedValue(strategy =
            GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String email;

    private String department;

}

What is a Repository?

A Repository is an interface responsible for database access.

Spring automatically creates its implementation during runtime.


Create Repository

EmployeeRepository.java

@Repository
public interface EmployeeRepository
        extends JpaRepository<Employee, Long> {

}

The first parameter represents the Entity class.

The second parameter represents the primary key type.


Built-In CRUD Operations

By extending JpaRepository, you automatically get:

save()

findById()

findAll()

deleteById()

count()

existsById()

No SQL required.


Save Data Example

Employee employee =
        new Employee();

employee.setName("Muhammad Zeeshan");

repository.save(employee);

Find Data Example

List<Employee> employees =
        repository.findAll();

Delete Data Example

repository.deleteById(1L);

Query Methods in Spring Data JPA

One of the best features of Spring Data JPA is automatic query generation.


Find By Name

List<Employee>
findByName(String name);

Spring automatically generates the SQL query.


Find By Department

List<Employee>
findByDepartment(String department);

Find By Email

Optional<Employee>
findByEmail(String email);

Multiple Conditions

List<Employee>
findByDepartmentAndName(
      String department,
      String name);

Sorting Data

Find All Employees Sorted By Name

repository.findAll(
    Sort.by("name"));

Descending Sort

repository.findAll(
    Sort.by(
      Sort.Direction.DESC,
      "name"));

Pagination

Pagination improves performance when working with large datasets.


Create Pageable Object

Pageable pageable =
        PageRequest.of(0, 5);

Fetch Page

Page<Employee> employees =
      repository.findAll(pageable);

Custom Queries Using @Query

Sometimes query methods are not enough.


JPQL Query Example

@Query("SELECT e FROM Employee e
        WHERE e.department = ?1")
List<Employee>
findEmployeesByDepartment(
        String department);

Native SQL Query

@Query(
 value =
 "SELECT * FROM employees
  WHERE department = ?1",
 nativeQuery = true)
List<Employee>
findEmployeesNative(
       String department);

Spring Data JPA Best Practices

Use DTOs

Avoid exposing Entity classes directly.

Use Pagination

Never load thousands of records at once.

Use Validation

Validate incoming requests.

Use Custom Queries Carefully

Prefer query methods whenever possible.

Create Proper Indexes

Improve database performance.


Common Mistakes

Using Entity Directly in APIs

Use DTOs instead.

Fetching Large Datasets

Use pagination.

Writing Unnecessary Queries

Use built-in repository methods.

Ignoring Database Indexes

Large applications require optimized indexes.


Interview Questions

What is Spring Data JPA?

Spring Data JPA simplifies database access by providing repository-based abstractions on top of JPA.


What is JpaRepository?

JpaRepository is an interface that provides built-in CRUD operations and additional database functionality.


What is the difference between JPA and Hibernate?

JPA is a specification.

Hibernate is one of its implementations.


What is the purpose of @Entity?

It marks a Java class as a database entity.


What is the purpose of @Repository?

It identifies a class or interface as a repository component responsible for data access.


FAQ

Is Spring Data JPA the same as Hibernate?

No. Spring Data JPA uses Hibernate (or another JPA implementation) underneath.

Can Spring Data JPA generate SQL automatically?

Yes. Query methods allow Spring to generate SQL automatically.

Is Spring Data JPA suitable for large applications?

Yes. It is widely used in enterprise applications.

Can I use PostgreSQL instead of MySQL?

Yes. Spring Data JPA supports many relational databases.


Continue Learning Spring Boot

Post a Comment

Please enter relevant questions and information.

Previous Post Next Post