Spring Data CrudRepository Interface Example
This article will focus on the implementation of Spring Data CrudRepository
interface into a Spring Boot project. CrudRepository
is used for generic CRUD (Create, Read, Update, And Delete) operation for a specific type. It extends Repository
interface which is a central repository marker interface. It takes the domain class to manage as well as the id type of the domain class as type arguments.
The CrudRepository
interface has 11 methods to perform the basic database operation:
1. <S extends T> S save(S entity)
→ Saves a given entity.
2. <S extends T> Iterable<S> saveAll(Iterable<S> entities)
→ Saves all given entities.
2. Optional<T> findById(ID id)
→ Retrieves an entity by its id.
4. boolean existsById(ID id)
→ Returns whether an entity with the given id exists.
5. Iterable<T> findAll()
→ Returns all instances of the type.
6. Iterable<T> findAllById(Iterable<ID> ids)
→ Returns all instances of the type with the given IDs.
7. long count()
→ Returns the number of entities available.
8. void deleteById(ID id)
→ Deletes the entity with the given id.
9. void delete(T entity)
→ Deletes a given entity.
10. void deleteAll(Iterable<? extends T> entities)
→ Deletes the given entities.
11. void deleteAll()
→ Deletes all entities managed by the repository.
Similar Posts:
What we’ll build
In this example, we will write the implementation class of CrudRepository
and perform the basic CRUD operation and save, retrieve, count, delete, etc customer data into a database.
Technology Used
Find the list of all technologies used in this application.
- Spring Tool Suite 4
- JDK 8
- Spring Boot 2.1.3.RELEASE
- Spring Data 2.1.5.RELEASE
- MySQL Database
- Maven 3
Database Schema
Find the table structure customers
managed by Spring Data in MySQL database.
If we set
spring.jpa.hibernate.ddl-auto=update
in the application.properties, table will be automatically created by Spring Data.
CREATE TABLE `customers` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`mobile` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`)
);
P.S Spring Data internally uses the Hibernate to manage the operations at the DAO layer.
Dependency Required
Below dependencies are must be in the project classpath. Add them to pom.xml.
<dependencies>
<!-- Spring boot data -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- spring boot web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MySQL database connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
application.properties
application.properties is a magical file in any Spring Boot project for the setup data source, JPA properties, MVC prefix & suffix, etc. Configuration in the application.properties file automatically read by Spring Boot.
# MySQL database connection strings
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=
# JPA property settings
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.show_sql=true
Entity Class
Customer
is an entity class.
package org.websparrow.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "customers")
public class Customer implements Serializable {
private static final long serialVersionUID = -7280187378770180724L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private String email;
private Long mobile;
// Generate getters and setters...
public Customer() { }
public Customer(String name, String email, Long mobile) {
super();
this.name = name;
this.email = email;
this.mobile = mobile;
}
public Customer(Integer id, String name, String email, Long mobile) {
super();
this.id = id;
this.name = name;
this.email = email;
this.mobile = mobile;
}
}
Repository Interface
Create a CostomerRepository
interface which extends CrudRepository
.
package org.websparrow.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.websparrow.entity.Customer;
@Repository
public interface CustomerRepository extends CrudRepository<Customer, Integer> {
}
For the demonstration, I have used the static data (hardcoded) and HTTP GET request but ideally, it comes from the front-end with appropriate HTTP method.
1. <S extends T> S save(S entity)
save(S entity)
method saves the given entity into the database.
@GetMapping("/save")
public Customer saveCustomer() {
Customer customer = new Customer("Sandeep Sharma", "[email protected]", 9876543210L);
return customerRepository.save(customer);
}
}
Output: To test it, hit the http://localhost:8080/customer/save, it saves the customer in the table.
2. <S extends T> Iterable<S> saveAll(Iterable<S> entities)
saveAll(Iterable<S> entities)
method saves the list of all given entities.
@GetMapping("/saveAll")
public Iterable<Customer> saveAllCustomer() {
List<Customer> customers = Arrays.asList(
new Customer("Gaurav Aggrawal", "[email protected]", 9876543210L),
new Customer("Prince Kumar", "[email protected]", 988776554L),
new Customer("Puneet Giri", "[email protected]", 123456789L),
new Customer("Anand Sharma", "[email protected]", 3728728273L)
);
return customerRepository.saveAll(customers);
}
Output: To test it, hit the http://localhost:8080/customer/saveAll, it saves all customers in the table.
3. Optional<T> findById(ID id)
findById(ID id)
method return an entity matches with its id.
@GetMapping("/findOne")
public Optional<Customer> findCustomerById() {
Integer id = 12151;
return customerRepository.findById(id);
}
Output: To test it, hit the http://localhost:8080/customer/findOne, it will return the customer matched with a given id.
4. boolean existsById(ID id)
existsById(ID id)
method true if the customer exists by id otherwise false.
@GetMapping("/exist")
public boolean isCustomerExist() {
Integer id = 12151;
return customerRepository.existsById(id);
}
Output: To test it, hit the http://localhost:8080/customer/exist. Returns true or false.
5. Iterable<T> findAll()
findAll()
method return the list give type entities managed by the repository.
@GetMapping("/all")
public Iterable<Customer> allCustomers() {
return customerRepository.findAll();
}
Output: To test it, hit the http://localhost:8080/customer/all.
6. Iterable<T> findAllById(Iterable<ID> ids)
findAllById(Iterable<ID> ids)
method also return the list give type entities matches with ids.
@GetMapping("/allById")
public Iterable<Customer> allCustomerById() {
List<Integer> ids = Arrays.asList(12154, 12155);
return customerRepository.findAllById(ids);
}
Output: To test it, hit the http://localhost:8080/customer/allById
7. long count()
count()
method returns the number of entities available in the table.
@GetMapping("/count")
public long countCustomer() {
return customerRepository.count();
}
Output: To test it, hit the http://localhost:8080/customer/count
8. void deleteById(ID id)
deleteById(ID id)
method delete the entity from table matched with the given id.
@GetMapping("/deleteOne")
public void deleteCustomerById() {
Integer id = 12151;
customerRepository.deleteById(id);
}
Output: To test it, hit the http://localhost:8080/customer/deleteOne
9. void delete(T entity)
delete(T entity)
method deletes the entity of given type.
@GetMapping("/deleteCustomer")
public void deleteCustomer() {
Customer customer = new Customer(12153, "Prince Kumar", "[email protected]", 988776554L);
customerRepository.delete(customer);
}
Output: To test it, hit the http://localhost:8080/customer/deleteCustomer
10. void deleteAll(Iterable<? extends T> entities)
deleteAll(Iterable<? extends T> entities)
method also deletes all entities of given type.
@GetMapping("/deleteCustomers")
public void deleteCustomers() {
List<Customer> customers = Arrays.asList(
new Customer(12154, "Puneet Giri", "[email protected]", 123456789L),
new Customer(12155, "Anand Sharma", "[email protected]", 3728728273L)
);
customerRepository.deleteAll(customers);
}
Output: To test it, hit the http://localhost:8080/customer/deleteCustomers
11. void deleteAll()
deleteAll()
method deletes all entities from the table managed by the repository.
@GetMapping("/deleteAll")
public void deleteAllCustomers() {
customerRepository.deleteAll();
}
Output: To test it, hit the http://localhost:8080/customer/deleteAll
Controller Class
Let’s see the complete controller class.
package org.websparrow.controller;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.websparrow.entity.Customer;
import org.websparrow.repository.CustomerRepository;
@RestController
@RequestMapping("/customer")
public class CustomerController {
@Autowired
private CustomerRepository customerRepository;
@GetMapping("/save")
public Customer saveCustomer() {
Customer customer = new Customer("Sandeep Sharma", "[email protected]", 9876543210L);
return customerRepository.save(customer);
}
@GetMapping("/saveAll")
public Iterable<Customer> saveAllCustomer() {
List<Customer> customers = Arrays.asList(new Customer("Gaurav Aggrawal", "[email protected]", 9876543210L),
new Customer("Prince Kumar", "[email protected]", 988776554L),
new Customer("Puneet Giri", "[email protected]", 123456789L),
new Customer("Anand Sharma", "[email protected]", 3728728273L));
return customerRepository.saveAll(customers);
}
@GetMapping("/findOne")
public Optional<Customer> findCustomerById() {
Integer id = 12151;
return customerRepository.findById(id);
}
@GetMapping("/exist")
public boolean isCustomerExist() {
Integer id = 12151;
return customerRepository.existsById(id);
}
@GetMapping("/all")
public Iterable<Customer> allCustomers() {
return customerRepository.findAll();
}
@GetMapping("/allById")
public Iterable<Customer> allCustomerById() {
List<Integer> ids = Arrays.asList(12154, 12155);
return customerRepository.findAllById(ids);
}
@GetMapping("/count")
public long countCustomer() {
return customerRepository.count();
}
@GetMapping("/deleteOne")
public void deleteCustomerById() {
Integer id = 12151;
customerRepository.deleteById(id);
}
@GetMapping("/deleteCustomer")
public void deleteCustomer() {
Customer customer = new Customer(12153, "Prince Kumar", "[email protected]", 988776554L);
customerRepository.delete(customer);
}
@GetMapping("/deleteCustomers")
public void deleteCustomers() {
List<Customer> customers = Arrays.asList(new Customer(12154, "Puneet Giri", "[email protected]", 123456789L),
new Customer(12155, "Anand Sharma", "[email protected]", 3728728273L));
customerRepository.deleteAll(customers);
}
@GetMapping("/deleteAll")
public void deleteAllCustomers() {
customerRepository.deleteAll();
}
}
Download Source Code: spring-data-crudrepository-interface-example.zip
References
- Spring Boot RESTful CRUD Example with MySQL Database
- Spring Data
- Interface CrudRepository<T,ID>
- Working with Spring Data Repositories