🚀 Introduction
The @Repository
annotation in Spring Boot is used to define a Data Access Object (DAO) or repository layer that interacts with the database.
✅ Handles database queries automatically
✅ Translates database exceptions into Spring-specific exceptions
✅ Works with JPA, JDBC, and other database technologies
This guide explains how to use @Repository
with examples.
1️⃣ What is @Repository?
The @Repository
annotation is a specialized version of @Component
, meaning Spring will automatically detect and register it as a bean.
It is used to define a class that:
✔ Interacts with a relational database (MySQL, PostgreSQL, etc.)
✔ Performs CRUD operations (Create, Read, Update, Delete)
✔ Works with Spring Data JPA, Hibernate, or JDBC
2️⃣ How @Repository Works with Spring Boot?
✅ Example: Defining a Simple Repository
@Repository
public class UserRepository {
public String getUserById(int id) {
return "Fetching user with ID: " + id;
}
}
📌 Spring will detect this class as a bean and allow injection into services.
3️⃣ Using @Repository with Spring Data JPA
Spring Boot simplifies database access using Spring Data JPA, which allows you to define repositories without writing SQL queries.
✅ Example: Creating a JPA Repository
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByName(String name); // Custom query method
}
📌 This repository provides built-in CRUD methods like save()
, findById()
, and deleteById()
.
4️⃣ @Repository Exception Handling (Automatic Translation)
Spring Boot automatically translates database-related exceptions into Spring’s DataAccessException
hierarchy.
✅ Example: Handling Database Errors
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void getUserById(Long id) {
try {
userRepository.findById(id).orElseThrow(() -> new RuntimeException("User not found"));
} catch (DataAccessException ex) {
System.out.println("Database error occurred: " + ex.getMessage());
}
}
}
📌 If there is a database error, @Repository
converts low-level exceptions into Spring exceptions.
5️⃣ Difference Between @Repository and @Service
Feature | @Repository |
@Service |
---|---|---|
Purpose | Data Access Layer (Database interactions) | Business Logic Layer (Service methods) |
Handles Exceptions | Converts database exceptions | Does not handle database exceptions |
Spring Component | Yes (@Component specialization) |
Yes (@Component specialization) |
Example Class | JPA Repository, JDBC DAO | Business logic implementation |
6️⃣ When to Use @Repository?
✔ When writing database access logic
✔ When working with Spring Data JPA, Hibernate, or JDBC
✔ When you need automatic exception translation
🚀 Use @Repository
for database-related operations and @Service
for business logic.
🔗 Bookmark this guide for quick reference! 🚀
Comments
Post a Comment
Leave Comment