In Spring Boot, DAO (Data Access Object), DTO (Data Transfer Object), and Repository are the parts. These parts work together within the layered architecture of application development but use different purposes. We need to know about the role of those parts of layered architecture in building clean, maintainable, and scalable applications by separating concerns, ensuring data encapsulation, and promoting code reusability. This topic will learn DAO vs DTO vs Repository, their use cases, and best practices for integrating them into our Spring Boot project.
What is DAO (Data Access Object)?
DAO is a design pattern used to encapsulate all data access logic. It abstracts the code that interacts directly with the database, usually via JPA, Hibernate, or JDBC.
Key Features
- Provides an interface between the application and database.
- Contains the manual implementation of data access methods.
- Often used in legacy systems or with custom queries.
- Annotated with @Repository.
Example: DAO Implementation
public interface UserDao {
User findById(Long id);
void save(User user);
}
@Repository
public class UserDaoImpl implements UserDao {
@PersistenceContext
private EntityManager entityManager;
public User findById(Long id) {
return entityManager.find(User.class, id);
}
public void save(User user) {
entityManager.persist(user);
}
}
What is Repository in Spring Boot?
A Repository in Spring Boot is a Spring Data JPA abstraction built on top of the DAO pattern. It eliminates boilerplate code and provides automatic implementations for standard CRUD operations.
Key Features
- Uses interface-based programming.
- Eliminates the need for custom DAO implementations.
- Supports query method derivation and @Query annotations.
- Integrated with Spring Data for seamless database interaction.
Example: UserRepository
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
Benefits
- Rapid development with minimal code.
- Integrated support for pagination, sorting, and specifications.
What is DTO?
A DTO is a simple Java object used to transfer data between layers of an application, especially between the service and controller layers, or to/from external clients (e.g., REST API).
Key Features
- Not persisted in the database.
- Contains only required fields.
- Helps hide internal structures (like Entity fields).
- Improves performance and security.
Example: UserDTO
public class UserDTO {
private String username;
private String email;
public UserDTO(String username, String email) {
this.username = username;
this.email = email;
}
// Getters and Setters
}
DAO vs DTO vs Repository
Feature | DAO(Data Access Object) | Repository | DTO(Data Transfer Object) |
Primary Role | Accessing the database manually | Auto-generated database interaction | Data transfer between layers |
Persistence | Yes, interacts directly with the database | Yes, interacts with the database via Spring Data | No, not stored in the database |
Implementation | Requires custom class and logic | Only interface; Spring provides implementation | Plain Java class with fields |
Used In | Legacy/custom solutions | Modern Spring Boot projects | REST APIs, controller-service communication |
Annotations | @Repository, @Transactional | @Repository or detected by Spring automatically | Typically none (may use Lombok annotations) |
Complex Logic | Suitable for custom queries | Limited; use custom repository if needed | None; holds and transfers data only |
When to Use DAO, Repository, and DTO
Use DAO When
- We are working in a legacy system.
- We need manual control over SQL or EntityManager logic.
- We require customized transactional control.
Use Repository When
- We are using Spring Data JPA in a modern application.
- We want to reduce boilerplate code.
- We prefer declarative query methods.
Use DTO When
- We are handling external API requests and responses.
- We need to hide entity fields or sensitive data.
- We want to reduce response size and improve security.
How They Work Together in a Spring Boot Application
Here’s how DAO, Repository, and DTO typically fit in a layered Spring Boot app:
+--------------------+
| Controller Layer | ← Sends/Receives DTOs
+--------------------+
↓
+--------------------+
| Service Layer | ← Uses Repositories or DAOs
+--------------------+
↓
+--------------------+
| Data Access Layer | ← Repositories or custom DAOs
+--------------------+
↓
+--------------------+
| Database |
+--------------------+
Sample Flow Using Repository and DTO
UserRepository.java
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
}
UserService.java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public UserDTO getUserByEmail(String email) {
User user = userRepository.findByEmail(email)
.orElseThrow(() -> new RuntimeException("User not found"));
return new UserDTO(user.getUsername(), user.getEmail());
}
}
UserController.java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/email/{email}")
public UserDTO getUser(@PathVariable String email) {
return userService.getUserByEmail(email);
}
}
Conclusion
In Spring Boot:
- DAO is a traditional manual data access logic pattern, used less in modern projects.
- A repository is the preferred approach in Spring Data, offering clean, declarative data access.
- DTO is useful for data transfer, especially in REST APIs, helping to ensure the separation of concerns and data encapsulation.
We can build clean, modular, and scalable applications by using each part appropriately.