0% found this document useful (0 votes)
14 views

Chapter III SpringBoot - Part 4 - Repository

Uploaded by

Mary Norssine
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Chapter III SpringBoot - Part 4 - Repository

Uploaded by

Mary Norssine
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

1

REPOSITORIES
SPRING DATA JPA / REPOSITORIES

§ In Spring Data JPA, a repository is a high-level abstraction over the data access layer.

§ It encapsulates the details of how data is stored, retrieved, and manipulated.

§ Repositories encapsulate the logic for querying the database. This includes both
standard CRUD operations (Create, Read, Update, Delete) as well as custom queries.

§ They act as a bridge between the application's business logic and the underlying
database. This separation of concerns keeps the business logic focused on its core
responsibilities.

2
SPRING DATA JPA / REPOSITORIES
Using repositories enables:

§ Eliminating repetitive code for common database operations. This leads to cleaner,
more maintainable code.

§ Establishing a standardized way of interacting with different types of entities. This


promotes code consistency and readability across the application.

§ Working with various data sources (relational databases, NoSQL databases, in-memory
databases). This flexibility allows switching between different storage mechanisms
without affecting the business logic.
3
SPRING DATA JPA / REPOSITORIES
Using repositories enables to:

§ Eliminate repetitive code for common database operations. This leads to cleaner, more
maintainable code.

§ Establish a standardized way of interacting with different types of datastores. This


promotes code consistency and readability across the application.

§ Work with various data sources (relational databases, NoSQL databases, in-memory
databases). This flexibility allows switching between different data storages without
affecting the business logic.
4
SPRING DATA JPA / REPOSITORIES
§ Work in conjunction with Spring's transaction management. They allow you to perform
multiple database operations within a single transaction, ensuring data integrity.

§ Since repositories abstract away the data access logic, it becomes easier to write unit
tests for the business logic without having to deal with actual database connections.

§ Repositories can be extended to incorporate caching mechanisms, which can


significantly improve the performance of data retrieval operations. This can be crucial in
applications with high read-to-write ratios.

§ Repositoriescan be used as a point of control for data access. You can implement
security measures, such as access control lists (ACLs), or apply data validation logic
before performing database operations.
5
SPRING DATA JPA / REPOSITORY TYPES
CrudRepository: is the most basic repository interface provided by Spring Data. It
provides basic CRUD (Create, Read, Update, Delete) operations for entities. It extends the
Repository interface and adds methods like save, findById, findAll, delete, etc.

JpaRepository: is an extension of CrudRepository that provides additional JPA-specific


methods. It inherits all the CRUD methods from CrudRepository and adds support for
pagination, sorting, and some convenience methods for working with JPA entities.

PagingAndSortingRepository: extends CrudRepository and adds methods for paginated


and sorted results. This is useful when dealing with large datasets where you want to
retrieve data in chunks.

JpaSpecificationExecutor: provides support for executing JPA Specifications.


Specifications are a way to dynamically build complex queries based on a set of criteria.
This interface can be combined with JpaRepository to perform advanced querying. 6
SPRING DATA JPA / JPA REPOSITORY
JpaRepository is an interface in Spring Data JPA that extends the CrudRepository
interface. It provides a set of predefined methods for common data access operations.
Using JpaRepository in Spring Data JPA to manipulate a JPA entity is quite straightforward.

1- Create a User Entity:


In this step, you define a Java class that represents a user. This class is annotated with
@Entity, which indicates that it's a JPA entity and should be mapped to a database table.

2- Create EntityRepository Interface:


You create an interface that extends JpaRepository<Entity, Long>. This interface acts as a
contract between your application and the Spring Data JPA framework.

7
SPRING DATA JPA / JPA REPOSITORY
1 2

8
SPRING DATA JPA / JPA REPOSITORY METHODS

§ save(S entity): Saves an entity. If the entity has an ID, it performs an update;
otherwise, it performs an insert.

§ saveAll(Iterable<S> entities): Saves multiple entities.

§ findById(ID id): Retrieves an entity by its primary key.

§ existsById(ID id): Checks if an entity with a given ID exists in the database.

§ findAll(): Retrieves all entities from the database.

§ findAllById(Iterable<ID> ids): Retrieves a list of entities by their IDs.

9
SPRING DATA JPA / JPA REPOSITORY METHODS

§ count(): Returns the total number of entities in the database.

§ delete(T entity): Deletes an entity from the database.

§ deleteById(ID id): Deletes an entity by its primary key.

§ deleteAll(Iterable<? extends T> entities): Deletes multiple entities.

§ deleteAll(): Deletes all entities from the database.

10
SPRING DATA JPA / JPA REPOSITORY CUSTOM QUERY METHODS

§ Custom query methods: in Spring Data JPA allow you to define repository
methods that perform specific queries on your entity without writing explicit JPQL
or native SQL queries.

§ These methods are derived from the method name itself, following a specific
naming convention.

11
SPRING DATA JPA / JPA REPOSITORY CUSTOM QUERY METHODS
Naming Convention:
§ Keyword: The method name should start with a keyword that indicates the type of

operation to perform. Common keywords include find, get, query, read, and count.

§ Entity Property: After the keyword, we specify the entity property to use for filtering or
retrieving data.

§ Condition: You can add a condition using keywords like By, followed by the property name in
CamelCase. This condition narrows down the query results.

§ Logical Operator: If you have multiple properties in the condition, you can use logical
operators like And, Or, or Between to connect them.

12
SPRING DATA JPA / JPA REPOSITORY CUSTOM QUERY METHODS
§ Finding by a Single Property:

List<User> findByLastName(String lastName);

§ Finding by Multiple Properties Using Logical Operators :

List<User> findByFirstNameAndLastName(String firstName, String lastName);

List<User> findByAgeGreaterThanAndGender(int age, String gender);

§ Counting Entities: long countByLastName(String lastName);

§ Deleting Entities: void deleteByFirstName(String firstName);

13
SPRING DATA JPA / JPA REPOSITORY CUSTOM QUERY METHODS
§ Ignoring Case: To perform case-insensitive searches, add IgnoreCase to the property
name:

List<User> findByFirstNameIgnoreCase(String firstName);

§ Negation: To negate a query condition, use Not:

List<User> findByLastNameNot(String lastName);

§ Returning Specific Fields: You can return specific fields of an entity by using projection,
which involves specifying the desired fields in the method name.

List<String> findEmailsByLastName(String lastName);


14
SPRING DATA JPA / JPA REPOSITORY CUSTOM QUERY METHODS

§ Handling Dates: For date properties, you can use keywords like Before, After, and
Between to create date-based queries.

List<User> findByBirthdateBefore(Date date);

List<User> findByBirthdateAfter(Date date);

List<User> findByBirthdateBetween(Date startDate, Date endDate);

15
SPRING DATA JPA / JPA REPOSITORY CUSTOM QUERY METHODS
Limitations:

§ Custom query methods can become complex and may not cover all possible query
scenarios.

§ Method name can become too long or complicated, it might lead to readability and
maintainability issues.

§ In such cases, you can use @Query annotation with JPQL or native SQL queries.

16
SPRING DATA JPA / JPA REPOSITORY
@Query annotations and JPQL:

§ The @Query annotation in Spring Data JPA allows you to define custom queries using
JPQL or native SQL queries. This gives you the flexibility to execute complex queries that
cannot be derived from method names alone.

§ JPQL (Java Persistence Query Language): is a query language defined by the Java
Persistence API (JPA) for querying entities in a database. JPQL is similar to SQL
(Structured Query Language) but is designed specifically for working with Java objects
and entity relationships rather than database tables.

17
SPRING DATA JPA / JPA REPOSITORY
Benefits of Using JPQL:

§ Portability: Queries work across different databases.

§ Object-Centric: Queries focus on Java objects and their properties.

§ Abstraction: Hides database-specific syntax.

§ Flexibility: Supports complex retrieval criteria.

§ Readability: More intuitive and maintainable than SQL.

§ Testing and Debugging: Easily test and debug within Java environment.

18
SPRING DATA JPA / JPA REPOSITORY
Simple Query: Retrieve all users with a specific last name

@Query("SELECT u FROM User u WHERE u.lastName = :lastName")


List<User> findByLastName(@Param("lastName") String lastName);

§ @Query indicates the start of a JPQL query.

§ "SELECT u FROM User u WHERE u.lastName = :lastName" is the JPQL query. It selects
entities of type User (u) where the lastName property matches the specified parameter
:lastName.

§ @Param("lastName") binds the lastName parameter in the method to the :lastName


parameter in the query.
19
SPRING DATA JPA / JPA REPOSITORY
Join Query: Retrieve all users who belong to a specific role

@Query("SELECT u FROM User u JOIN u.roles r WHERE r.name = :roleName")


List<User> findByRole(@Param("roleName") String roleName);

§ This example involves a join operation between the User entity (u) and the Role entity
(r). It retrieves users (u) who have roles (r) with a specified name.

§ JOIN u.roles r specifies the join operation between the User entity's roles property and
the Role entity, aliasing the latter as r.

20
SPRING DATA JPA / JPA REPOSITORY
Aggregation Function: Retrieve the total number of users.

@Query("SELECT COUNT(u) FROM User u")


Long countUsers();

§ In this example, COUNT(u) is an aggregation function that counts the number of User

entities (u).

§ The query retrieves the count of users without specifying any conditions.

21
SPRING DATA JPA / JPA REPOSITORY
Subquery: Retrieve users whose age is greater than the average age.

@Query("SELECT u FROM User u WHERE u.age > (SELECT AVG(u2.age) FROM User u2)")
List<User> findByAgeGreaterThanAverage();

§ This example involves a subquery.

§ The subquery calculates the average age of all users

(SELECT AVG(u2.age) FROM User u2)

which is then used as a comparison in the main query.

22

You might also like