In the previous tutorial, we have seen what is Spring Data JPA?
In this quick tutorial, we will learn how to use the Spring Data JPA repository in the Spring Boot application.
In order to use Spring Data JPA in the Spring boot application, first, you need to add the below dependency to your Spring boot application:
<dependency>
<groupId>org.springframework.boot
<artifactId>spring-boot-starter-data-jpa
</dependency>
Next, you need to configure the database in your Spring boot application.
For example, if you are using MySQL database, then add MySQL JDBC driver dependency:
<dependency>
<groupId>com.mysql
<artifactId>mysql-connector-j
<scope>runtime
</dependency>
Also, you need to configure MySQL details in the application.properties
file
to connect the Spring boot application with the MySQL database:
Open the application.properties
file and add the following configuration to
it:
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useSSL=false
spring.datasource.username=root
spring.datasource.password=Mysql@123
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
Make sure that you will create a demo database before running the Spring boot application.
Also, change the MySQL username and password as per your MySQL installation on your machine.
Once you have set up a database connection with your Spring boot application then here are the steps to use the Spring Data JPA repository.
JpaRepository
interfaceJpaRepository
interfaceConsider we have a Product
entity. Now let's create a ProductRepository
that extends JpaRepository
and add
the following code to it:
import java.util.List;
import net.javaguides.springdatajpacourse.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository {
}
Spring Data JPA query methods are the most powerful methods, we can create query methods to select the records from the database without writing SQL queries. Behind the scenes, Spring Data JPA will create SQL queries based on the query method and execute the query for us.
For example:
import com.springboot.crud.example.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository {
Product findByName(String name);
}
This is a query method:
Product findByName(String name);
We can create a ProductService
class and then inject ProductRepository
using @Autowired
annotation to use it's methods:
import com.springboot.crud.example.entity.Product;
import com.springboot.crud.example.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProductService {
@Autowired
private ProductRepository repository;
public Product saveProduct(Product product) {
return repository.save(product);
}
public List saveProducts(List products) {
return repository.saveAll(products);
}
public List getProducts() {
return repository.findAll();
}
public Product getProductById(int id) {
return repository.findById(id).orElse(null);
}
public Product getProductByName(String name) {
return repository.findByName(name);
}
public String deleteProduct(int id) {
repository.deleteById(id);
return "product removed !! " + id;
}
public Product updateProduct(Product product) {
Product existingProduct = repository.findById(product.getId()).orElse(null);
existingProduct.setName(product.getName());
existingProduct.setQuantity(product.getQuantity());
existingProduct.setPrice(product.getPrice());
return repository.save(existingProduct);
}
}
Well, these are the three simple steps to use the Spring Data JPA repository
Let's create a complete end-to-end Spring boot project to demonstrate the usage of Spring Data JPA.
We’ll use Spring initializr web tool to bootstrap our application.
Go to http://start.spring.io
Select Java in the language section.
Enter Artifact as spring-boot-crud-example
Add Web, Lombok, JPA, and MySQL dependencies.
Click Generate to generate and download the project.
Once the project is generated, unzip it and import it into your favorite IDE.
Open the pom.xml
file and confirm below dependencies are present:
<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>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
Let's first create a database named "demo" in the MySQL server.
Now, let's configure MySQL database URL, username, and password so that Spring Boot can create a Data source.
Open src/main/resources/application.properties
file and add the following
properties to it -
spring.datasource.url = jdbc:mysql://localhost:3306/demo?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false
spring.datasource.username = root
spring.datasource.password = root
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.ddl-auto = update
Change spring.datasource.username
and spring.datasource.password
as per your MySQL installation.
Note that, I’ve set spring. jpa.hibernate.ddl-auto
property to update. This
property updates the database
schema whenever you create or modify the domain models in your application.
Create a Product
class with the following content into it:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import jakarta.persistence.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "PRODUCT_TBL")
public class Product {
@Id
@GeneratedValue
private int id;
private String name;
private int quantity;
private double price;
}
Create ProductRepository
interface with the following content into it:
import com.springboot.crud.example.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository {
Product findByName(String name);
}
Create a ProductService
class with the following content into it:
import com.springboot.crud.example.entity.Product;
import com.springboot.crud.example.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProductService {
@Autowired
private ProductRepository repository;
public Product saveProduct(Product product) {
return repository.save(product);
}
public List saveProducts(List products) {
return repository.saveAll(products);
}
public List getProducts() {
return repository.findAll();
}
public Product getProductById(int id) {
return repository.findById(id).orElse(null);
}
public Product getProductByName(String name) {
return repository.findByName(name);
}
public String deleteProduct(int id) {
repository.deleteById(id);
return "product removed !! " + id;
}
public Product updateProduct(Product product) {
Product existingProduct = repository.findById(product.getId()).orElse(null);
existingProduct.setName(product.getName());
existingProduct.setQuantity(product.getQuantity());
existingProduct.setPrice(product.getPrice());
return repository.save(existingProduct);
}
}
Create ProductController
class with the following content into it:
import com.springboot.crud.example.entity.Product;
import com.springboot.crud.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class ProductController {
@Autowired
private ProductService service;
@PostMapping("/addProduct")
public Product addProduct(@RequestBody Product product) {
return service.saveProduct(product);
}
@PostMapping("/addProducts")
public List addProducts(@RequestBody List products) {
return service.saveProducts(products);
}
@GetMapping("/products")
public List findAllProducts() {
return service.getProducts();
}
@GetMapping("/productById/{id}")
public Product findProductById(@PathVariable int id) {
return service.getProductById(id);
}
@GetMapping("/product/{name}")
public Product findProductByName(@PathVariable String name) {
return service.getProductByName(name);
}
@PutMapping("/update")
public Product updateProduct(@RequestBody Product product) {
return service.updateProduct(product);
}
@DeleteMapping("/delete/{id}")
public String deleteProduct(@PathVariable int id) {
return service.deleteProduct(id);
}
}
We’ve successfully built all the APIs for our application. Let’s now run the app and test the APIs.
Just go to the root directory of the application and type the following command to run it -
$ mvn spring-boot:run
The application will start at Spring Boot’s default tomcat port 8080.
In this tutorial, we have seen how to use the Spring Data JPA repository interface in the Spring boot project. We have also created a complete example to demonstrate the usage of Spring data JPA end to end.