Last updated on April 8th, 2024
We need to create a JPA entity class and then create an interface that extends JpaRepository interface by providing that entity class name and the data type of the @Id annotation annotated property of that entity class. After this, we are adding custom methods to that created interface by using JPA query methods with properties of that JPA entity class. In this topic, we will learn about how to add custom method in the JPA Repository in the Spring Boot Application. We will create a restful web service Spring Boot Application using Maven, Spring Web, Spring Data JPA, Lombok, and H2 database.
JPA Query Methods
JPA provides us with ready-made methods to create a query from the method name. This query method helps to execute the query in the database through Java code without the need to write explicit queries.
Example
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
List<Employee> findByName(String names);
}
To explain adding custom we will use the findBy column name with the help query method of JPA which ready-made method to execute a select query based on the property name of the JPA entity class. In the above, we have used a list of employees according name property of the Employee class.
Let’s implement to add custom methods in JpaRespository using JPA query methods in Spring Boot Application step-by-step.
1. Creating a Spring Boot Starter Project
We are creating a Spring Boot Application from the web tool Spring Initializr or you can create it from the IDE(STS, VS Code etc.) you are using.
Add the following dependencies:
- Spring Web
- Spring Data JPA
- Lombok
- H2 Database
2. Keep the IDE ready
We are importing this created application into our Eclipse IDE or you can import it into another IDE you are using. You can refer to this article to create and set up the Spring Boot Project in Eclipse IDE.
Project Structure of Add Custom Method in JPA Repository
3. Maven Dependency
Here is the complete pom.xml file for the Spring Boot Application.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath />
<!-- lookup parent from repository -->
</parent>
<groupId>com.springjava</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
4. Defining the configuration
We are configuring the H2 database configuration in the application.properties file.
application.properties
# H2 Database Configuration
spring.datasource.url=jdbc:h2:mem:test
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
5. Creating a JPA Entity
We are creating a JPA entity class Employee with these properties(id, name, email, and mobileNo).
Employee.java
package com.springjava.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Data;
@Data
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private String mobileNo;
}
- This @Data annotation is used for a constructor, setter method, getter method etc.
- This @Entity annotation is used to create a table through Java code in the database.
6. Creating a JPA Repository
We are a JPA Repository to interact with the JPA Entity class and use query method for the persistence operation in the table employee and add three custom methods in this repository for executing queries from the method name.
EmployeeRepository.java
package com.springjava.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.springjava.entity.Employee;
public interface EmployeeRepository extends JpaRepository < Employee, Long > {
List < Employee > findByName(String name);
Employee findByEmail(String email);
Employee findByMobileNo(String mobNo);
}
- We used query methods of JPA for adding custom methods in the repository findByProperty_Name(). Property_Name is the property of the JPA Entity class i.e. Employee.
7. Creating a Service Interface
We are creating a Service interface with some method declaration(save(), findByName(), findByEmail()and findByMobileNo()).
EmployeeService.java
package com.springjava.service;
import java.util.List;
import com.springjava.entity.Employee;
public interface EmployeeService {
void save(Employee employee);
List < Employee > findByName(String name);
Employee findByEmail(String email);
Employee findByMobileNo(String mobNo);
}
8. Creating a Service class
We are creating a Service class EmployeeServiceImpl and this class is implementing the EmployeeService interface. This class is annotated with @Service annotation to act service for this Spring Boot application with Spring Data JPA.
EmployeeServiceImpl.java
package com.springjava.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springjava.entity.Employee;
import com.springjava.repository.EmployeeRepository;
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
EmployeeRepository empRepo;
@Override
public void save(Employee employee) {
empRepo.save(employee);
}
@Override
public List < Employee > findByName(String name) {
return empRepo.findByName(name);
}
@Override
public Employee findByEmail(String email) {
return empRepo.findByEmail(email);
}
@Override
public Employee findByMobileNo(String mobNo) {
return empRepo.findByMobileNo(mobNo);
}
}
9. Creating a Rest Controller class
We are creating a RestController class EmployeeController in which all methods are created for API endpoints
EmployeeController.Java
package com.springjava.controller;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.springjava.entity.Employee;
import com.springjava.service.EmployeeService;
@RestController
@RequestMapping("/api/employee")
public class EmployeeController {
@Autowired
EmployeeService empService;
@PostMapping("/save")
public ResponseEntity < ? > saveEmployee(@RequestBody Employee employee) {
Map < String, Object > respEmp = new LinkedHashMap < String, Object > ();
empService.save(employee);
respEmp.put("status", 1);
respEmp.put("message", "Record is Saved Successfully!");
return new ResponseEntity < > (respEmp, HttpStatus.CREATED);
}
@GetMapping("/list/{name}")
public ResponseEntity < ? > getEmployees(@PathVariable String name) {
Map < String, Object > respEmp = new LinkedHashMap < String, Object > ();
List < Employee > empList = empService.findByName(name);
if (!empList.isEmpty()) {
respEmp.put("status", 1);
respEmp.put("data", empList);
return new ResponseEntity < > (respEmp, HttpStatus.OK);
} else {
respEmp.clear();
respEmp.put("status", 0);
respEmp.put("message", "Data is not found");
return new ResponseEntity < > (respEmp, HttpStatus.NOT_FOUND);
}
}
@GetMapping("/by-email/{email}")
public ResponseEntity < ? > getEmployeeByEmail(@PathVariable String email) {
Map < String, Object > respEmp = new LinkedHashMap < String, Object > ();
try {
Employee emp = empService.findByEmail(email);
respEmp.put("status", 1);
respEmp.put("data", emp);
return new ResponseEntity < > (respEmp, HttpStatus.OK);
} catch (Exception ex) {
respEmp.clear();
respEmp.put("status", 0);
respEmp.put("message", "Data is not found");
return new ResponseEntity < > (respEmp, HttpStatus.NOT_FOUND);
}
}
@GetMapping("/by-mobile/{mob}")
public ResponseEntity < ? > getEmployeeByMob(@PathVariable String mob) {
Map < String, Object > respEmp = new LinkedHashMap < String, Object > ();
try {
Employee emp = empService.findByMobileNo(mob);
respEmp.put("status", 1);
respEmp.put("data", emp);
return new ResponseEntity < > (respEmp, HttpStatus.OK);
} catch (Exception ex) {
respEmp.clear();
respEmp.put("status", 0);
respEmp.put("message", "Data is not found");
return new ResponseEntity < > (respEmp, HttpStatus.NOT_FOUND);
}
}
}
10. Run the Spring Boot Application and Check
To this Spring Boot application, Right-Click on the DemoApplication.java then click on Run As, and select Java Application.
Check H2 Database
Check the H2 database console and browse this URL “http://localhost:8080/h2-console”.
See the below table here:
Testing API on the Postman
Saving the employee data
POST: http://localhost:8080/api/employee/save
Check the table:
Retrieving the employee data
GET: http://localhost:8080/api/employee/list/test
Retrieving the employee data by email
GET: http://localhost:8080/api/employee/by-email/test@gmail.com
Retrieving the employee by mobileNo
GET: http://localhost:8080/api/employee/by-mobile/1234567890
Conclusion
In this topic, we learnt about how to add custom methods in JpaRepository in the Spring Boot restful web services application using the query method of the JPA findByColumnName() method