Spring Boot Tutorial
Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)
Prerequisite (Spring Core Concepts)
Spring Boot Core
Spring Boot with REST API
Spring Boot with Database and Data JPA
Spring Boot with Kafka
Spring Boot with AOP
In Spring Boot, the JpaRepository
interface provides a set of standard CRUD operations for working with relational databases. It is a part of the Spring Data JPA project, which simplifies database interactions by reducing boilerplate code. When you extend JpaRepository
, you get several methods for free, like save()
, findAll()
, findById()
, delete()
, etc.
Let's walk through a basic example to see how JpaRepository
works in a Spring Boot application.
Include the required dependencies in your pom.xml
:
<!-- Spring Boot Starter Data JPA --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- Your Database Driver, e.g., H2 for demonstration purposes --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency>
Let's assume we are working with a User
entity:
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String email; // Getters, setters, constructors... }
Create a repository interface for the User
entity:
import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, Long> { // This is all you need for basic CRUD operations! // You can add custom query methods if needed. }
Now, let's use the repository in a service:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class UserService { @Autowired private UserRepository userRepository; public List<User> getAllUsers() { return userRepository.findAll(); } public Optional<User> getUserById(Long id) { return userRepository.findById(id); } public User saveUser(User user) { return userRepository.save(user); } public void deleteUser(Long id) { userRepository.deleteById(id); } // ... other methods as required }
Configure your data source in the application.properties
or application.yml
file:
# H2 database configurations (replace for other databases) spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.h2.console.enabled=true # Hibernate configurations spring.jpa.hibernate.ddl-auto=update
With these configurations, Spring Boot will use an in-memory H2 database and Hibernate will update the schema as per your entities.
Now, you can run your application, inject the UserService
into a controller or another component, and use the methods to interact with your database.
Remember, with Spring Data JPA and JpaRepository
, a lot of the implementation details are abstracted away, letting you focus on the business logic. Custom queries can also be added to the repository by just defining method signatures, without the need for an implementation. This is made possible due to the proxy objects created by Spring Data JPA at runtime.
CRUD operations with JpaRepository in Spring Boot:
JpaRepository
to perform standard CRUD operations (Create, Read, Update, Delete) in a Spring Boot application.public interface YourEntityRepository extends JpaRepository<YourEntity, Long> { // JpaRepository provides methods like save, findById, findAll, deleteById, etc. }
Custom queries with JpaRepository in Spring Boot:
@Query
annotations.public interface YourEntityRepository extends JpaRepository<YourEntity, Long> { List<YourEntity> findBySomeField(String someFieldValue); @Query("SELECT e FROM YourEntity e WHERE e.someField = :value") List<YourEntity> customQuery(@Param("value") String value); }
Pagination and sorting with JpaRepository in Spring Boot:
Pageable
with JpaRepository
.public interface YourEntityRepository extends JpaRepository<YourEntity, Long> { Page<YourEntity> findBySomeField(String someFieldValue, Pageable pageable); }
Entity relationships and associations with JpaRepository in Spring Boot:
JpaRepository
.@Entity public class ParentEntity { @OneToMany(mappedBy = "parent") private List<ChildEntity> children; } @Entity public class ChildEntity { @ManyToOne @JoinColumn(name = "parent_id") private ParentEntity parent; }
NamedQuery and native queries with JpaRepository in Spring Boot:
@NamedQuery
for named queries or execute native SQL queries with @Query
and nativeQuery = true
.@Entity @NamedQuery(name = "YourEntity.findBySomeField", query = "SELECT e FROM YourEntity e WHERE e.someField = :value") public class YourEntity { // Entity fields and annotations } public interface YourEntityRepository extends JpaRepository<YourEntity, Long> { List<YourEntity> findBySomeField(@Param("value") String value); @Query(value = "SELECT * FROM your_entity WHERE some_field = :value", nativeQuery = true) List<YourEntity> customNativeQuery(@Param("value") String value); }
JpaRepository auditing and versioning in Spring Boot:
@Entity @EntityListeners(AuditingEntityListener.class) public class YourEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @CreatedDate private LocalDateTime createdDate; @LastModifiedDate private LocalDateTime lastModifiedDate; @Version private Long version; // Other entity fields and annotations }
Transaction management with JpaRepository in Spring Boot:
JpaRepository
operations to ensure consistency and atomicity.@Service @Transactional public class YourEntityService { @Autowired private YourEntityRepository entityRepository; public YourEntity saveEntity(YourEntity entity) { return entityRepository.save(entity); } }