Getting Started With Spring Data JPA

  • By Shital Chauhan
  • November 6, 2024
  • JAVA Programming
Getting Started With Spring Data JPA

Getting Started With Spring Data JPA

Spring Data JPA is part of the larger Spring Data project and provides a powerful, easy-to-use framework for managing relational data in Java applications. It simplifies database access by offering repository abstractions, reducing boilerplate code, and allowing developers to focus on business logic. Getting started with Spring Data JPA! Learn how to simplify database operations in Java, with easy setup, CRUD operations, and best practices for data access.

 

Key Features

  1. Repository Support: Spring Data JPA allows you to create repositories that encapsulate CRUD operations. By extending interfaces like JpaRepository, you can perform database operations without writing boilerplate code.
  2. Automatic Query Generation: Spring Data JPA can generate queries based on method names in the repository interface, allowing you to define custom query methods without the need for additional configuration.
  3. Auditing: It supports automatic tracking of entity changes, such as creation and modification timestamps, which can be configured easily.
  4. Pagination and Sorting: The framework provides built-in support for pagination and sorting, making it easier to manage large datasets.

 

For Free, Demo classes Call: 020-71173125

Registration Link: Java Classes in Pune!

 

Example:

Step 1: To start using Spring Data JPA, we have to include the necessary dependencies in our project. For Maven, we can add:

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

 

Step2: Configuration 

Configure the database in application.properties file

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

spring.datasource.username= userName 

spring.datasource.password=password 

spring.jpa.hibernate.ddl-auto=update

 

Step3: Define the Entity Classes

Create an Employee entity class to represent the employee records:

import javax.persistence.*; 

@Entity @Table(name = “employees”) 

public class Employee {

 @Id @GeneratedValue(strategy = GenerationType.IDENTITY) 

private Long id; 

private String name; 

private String position; 

// Getters and setters

 public Long getId() 

{ return id; } 

public void setId(Long id) 

{ this.id = id; }

public String getName() { return name; } 

public void setName(String name)

 { this.name = name; } 

public String getPosition() 

{ return position; } 

public void setPosition(String position) 

{ this.position = position; } }

 

Step 4: Create the Repository

Create an EmployeeRepository interface that extends JpaRepository:

import org.springframework.data.jpa.repository.JpaRepository;

public interface EmployeeRepository extends JpaRepository<Employee, Long> {

}

 

Here we don’t have to write the declaration of crud methods, Spring Data JPA provides the inbuilt implementation of basic crud operation for example:

findAll(), save(), findById(), deleteById() etc…

 

Step 5: Create the Service

Create a service class to handle business logic:

Service class defines the business logic methods that will be called in the controller

By auto-wiring the reference of service in the controller

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.List;

@Service

public class EmployeeService {

  @Autowired

    private EmployeeRepository employeeRepository;

  public List<Employee> getAllEmployees() {

        return employeeRepository.findAll();}

 public Employee getEmployeeById(Long id) {

        return employeeRepository.findById(id).orElse(null); }

public Employee createEmployee(Employee employee) {

        return employeeRepository.save(employee);}

public Employee updateEmployee(Long id, Employee employeeDetails) {

        Employee employee = employeeRepository.findById(id).orElse(null);

        if (employee != null) {

            employee.setName(employeeDetails.getName());

            employee.setPosition(employeeDetails.getPosition());

            return employeeRepository.save(employee); 

     }

        return null;

}public void deleteEmployee(Long id) {

        employeeRepository.deleteById(id);}

}

 

Step 6: Create a controller class to handle HTTP requests:

import org.springframework.beans.factory.annotation.Autowired; 

import org.springframework.http.ResponseEntity; 

import org.springframework.web.bind.annotation.*;

 import java.util.List; 

@RestController 

@RequestMapping(“/api/employees”) 

public class EmployeeController

 { 

@Autowired private 

EmployeeService employeeService; 

@GetMapping 

public List<Employee> getAllEmployees()

 { 

return employeeService.getAllEmployees(); 

@GetMapping(“/{id}”) 

public ResponseEntity<Employee> getEmployeeById(@PathVariable Long id) {

 Employee employee = employeeService.getEmployeeById(id);

 return employee != null ? ResponseEntity.ok(employee) : ResponseEntity.notFound().build();

 }

@PostMapping 

public Employee createEmployee(@RequestBody Employee employee) { 

return employeeService.createEmployee(employee); 

@PutMapping(“/{id}”) 

public ResponseEntity<Employee> updateEmployee(@PathVariable Long id, @RequestBody Employee employeeDetails) 

{

 Employee updatedEmployee = employeeService.updateEmployee(id, employeeDetails); return updatedEmployee != null ? ResponseEntity.ok(updatedEmployee) : ResponseEntity.notFound().build(); 

@DeleteMapping(“/{id}”) 

public ResponseEntity<Void> deleteEmployee(@PathVariable Long id) { employeeService.deleteEmployee(id); return ResponseEntity.noContent().build(); 

} }

 

Step 7: Testing the Application

  1. Run the Spring Boot application.
  2. Access  the  url at http://localhost:8080/api/employees to view the

      database records.

  1. Use a tool like Postman to test the CRUD operations:
    • Create an employee: POST to /api/employees with a JSON body (e.g., {“name”: “John Doe”, “position”: “Developer”})
    • Get all employees: GET to /api/employees
    • Get an employee by ID: GET to /api/employees/{id}
    • Update an employee: PUT to /api/employees/{id} with updated JSON body
    • Delete an employee: DELETE to /api/employees/{id}

 

Conclusion:

Data JPA is a specification for hibernate, it provides built-in crud methods to whom we don’t have to give the implementation, and it also provides the method for pagination to load more content on the web page. Hibernate is one of the JPA providers. 

It uses platform independent query language like JPQL(Java Persistence Query Language) through which it simplifies the managing relational database in java applications.

 

Note: Do watch our latest video: Click Here

 

Author:-

Shital Chauhan
Call the Trainer and Book your free demo class for Java now!!!

© Copyright 2020 | SevenMentor Pvt Ltd.

Submit Comment

Your email address will not be published. Required fields are marked *

*
*