Chapter III SpringBoot - Part 4 - Repository
Chapter III SpringBoot - Part 4 - Repository
REPOSITORIES
SPRING DATA JPA / REPOSITORIES
§ In Spring Data JPA, a repository is a high-level abstraction over the data access layer.
§ 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.
§ 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.
§ 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.
§ 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.
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.
9
SPRING DATA JPA / JPA REPOSITORY METHODS
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:
13
SPRING DATA JPA / JPA REPOSITORY CUSTOM QUERY METHODS
§ Ignoring Case: To perform case-insensitive searches, add IgnoreCase to the property
name:
§ Returning Specific Fields: You can return specific fields of an entity by using projection,
which involves specifying the desired fields in the method name.
§ Handling Dates: For date properties, you can use keywords like Before, After, and
Between to create date-based queries.
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:
§ 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
§ "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.
§ 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.
§ 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();
22