Spring Data Repository interface Examples
There are different kinds of Spring Data repository interfaces and their
functionality. In this tutorial, we are going to discuss,
- CrudRepository
- PagingAndSortingRepository
- JpaRepository
Every repository which is mentioned above extends the generic Repository
interface and they each are responsible for different functionality.
Spring Data Hierarchy defines the Repository (marker interface) as the top-level interface.
1. Crud Repository Example
CrudRepository is a Spring Data interface for generic CRUD operations on a repository of a specific type. It provides several methods out of the box for interacting with a database. So we will into this using the example given below.
Dependencies need
Add the following spring-data-jpa and h2 database to your pom.xml file in
the spring project.
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>runtime</version>
</dependency>
Example application.
So in here, we create the Student bean which is the Spring Data entity.
This class will define the data types that will get persisted to the
database when we call the save() method.
@Entity(name = "Student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(unique = true)
private String studentId;
private String studentName;
}
So next thing that has to do is create the CrudRepository interface to
work with the Student entity.
@Repository
public interface studentRepository extends CrudRepository<Student, Long> {
}
When an instance of this repository is instantiated, the underlying logic
will automatically be in place for working with the Student Entity class.
So after the repository is instantiated, in order to save it to the
database we have to use the created object from the Student class.
StudentRepository repo = context.getBean(StudentRepository.class);
Student student = new Student("IT8985451", "George Oliver");
student = repo.save(student);
This will create a new entry in the database table for StudentEntity.As
we did not specify the id value for the student record, the id will
auto-increment as we declared it in the Student Entity. The save method
will return the saved entity.
Other than the can use the save() method to update an existing entry to
our database. Think, if you want to update the above entity that we have
already created. Can use the CRUDRepository method findById to get the
entity from the database and update its values.
Student student = repo.findByStudentId(StudentId).get();
student.setName("George Charlie");
repo.save(student);
So in here, the relevant student’s name will be changed to “George
Charlie” with the help of the CRUDRepository method.
Some of the crud functionalities as a brief,
save() – Save an iterable of entities. Here we can pass multiple
objects to save them in a batch.
findAll() – get all the entities in the database.
findOne() – get a single entity
count() – count no of entities available in the database.
Delete() – delete an entity based on the passed object.
So these generic examples are providing the
query abstractions
needed in an application
2. PagingAndSortingRepository Example
extension of CrudRepository to provide additional methods to retrieve entities using the pagination and sorting abstraction. This provides two methods.
Page findAll(Pageable pageable) – returns a Page of entities
meeting the paging restriction provided in the Pageable object.
Iterable findAll(Sort sort) – returns all entities sorted by the
given options. No paging is applied here.
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface StudentRepository extends
PagingAndSortingRepository < Student, Long > {
}
So using this PagingAndSortingRepository, if you want to set sorted by
name with a limited number of records(given no of records), we can achieve
it by using the below code snippet.
Sort sort = new Sort(new Sort.Order(Direction.ASC, "studentName"));
Pageable pageable = new PageRequest(0, 20, sort);
So that’s the explanation about PagingAndSortingRepository in the data
repository interface.
3. JpaRepository Example
JpaRepository provides some JPA-related methods such as flushing the persistence context and deleting records in a batch. Because of the inheritance mentioned above, JpaRepository will have all the functions of CrudRepository and PagingAndSortingRepository.
Main features in JpaRepository,
JpaRepository extends PagingAndSortingRepository that extends CrudRepository.
JpaRepository provides CRUD and pagination operations, along with
additional methods like flush(), saveAndFlush(),
and deleteInBatch(), etc.
The return type of the saveAll() method is a List.
Use Case - To perform CRUD as well as batch operations, define repository
extends JpaRepository.
import org.springframework.stereotype.Repository;
interface ReadOnlyRepository<T> extends Repository<T, Long> {
}
Methods support in,
findAll() – get a List of all available entities in
database
findAll(…) – get a List of all available entities and sort
them using the provided condition
save(…) – save an Iterable of entities. Here, we can pass
multiple objects to save them in a batch
flush() – flush all pending task to the database
saveAndFlush(…) – save the entity and flush changes immediately
deleteInBatch(…) – delete an Iterable of entities. Here, we can pass multiple objects to delete them in a batch
Difference between CrudRepository, JpaReposistory, PangingAndSortingRepository in Spring Data JPA?
Summary
That's all about Spring Data Repository interfaces in Java. This article covered important differences and features of the Spring Data Repository interface. You have also learned about CrudRepository, JpaReposistory, PangingAndSortingRepository, and their differences, and most importantly when to use them and how to use them. So that’s all about the Spring data repository interface. Hope you enjoy it. See you in the next tutorial.
Other Spring Framework articles you may like to explore
- What is the use of DispatcherServlet in Spring MVC?
- 15 Spring Data JPA Interview Questions with Answers
- Top 10 Courses to Learn Microservices with Spring Boot
- 13 Spring Boot Actuator Questions for interviews
- 10 Best Spring Framework Courses for Beginners
- 20+ Spring Boot Interview Questions for Java developers
- 20 Spring Boot Testing Interview Questions with Answers
- 10 Advanced Spring Boot Courses for Experienced Developers
- 15 Spring Cloud Interview Questions with Answers
- How to limit the number of concurrent active sessions in Java web app
- How to implement LDAP authentication in the Active directory
- Top 15 Microservice Interview Questions with Answers
- How to get ServletContext object in Spring controller
- Difference between @RestController and @Controller in Spring MVC?
- How Spring MVC works internally?
- How to enable Spring security in a Java web application?
- 17 Spring AOP Interview Questions with Answers
Thanks for reading this article so far. If you find this Spring Data JPA
tutorial and different Repository interface examples like JpaRepository,
and CrudRepository useful, please share them with your friends and
colleagues. If you have any questions or feedback, then please drop a
note.
No comments:
Post a Comment