← Back to Home
Spring Data JPA
Spring Data JPA simplifies database access by providing repository abstractions that eliminate boilerplate code. It builds on top of JPA (Java Persistence API) and offers powerful features like query methods, pagination, and auditing with minimal configuration.
Key Features
Repository Abstraction
Extend JpaRepository to get CRUD operations, pagination, and sorting without writing implementation code.
Query Methods
Define queries by method names following Spring Data conventions, automatically generating SQL queries.
Custom Queries
Use @Query annotation to write custom JPQL or native SQL queries when needed.
Pagination & Sorting
Built-in support for pagination and sorting with Pageable and Sort interfaces.
Use Cases
- CRUD Operations: Simplifying create, read, update, and delete operations
- Complex Queries: Building dynamic queries based on method names
- Data Access Layer: Creating a clean separation between business logic and data access
- Multi-database Support: Working with various relational databases (MySQL, PostgreSQL, H2, etc.)
- Auditing: Automatically tracking entity creation and modification dates
Example Usage
Define a repository interface:
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByEmail(String email);
List<User> findByAgeGreaterThan(int age);
@Query("SELECT u FROM User u WHERE u.active = true")
List<User> findActiveUsers();
Page<User> findByLastName(String lastName, Pageable pageable);
}
Dependencies
Add the following dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Configuration
Configure database connection in application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true