DAO vs DTO vs Repository

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.

DAO vs DTO vs Repository

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

FeatureDAO(Data Access Object)RepositoryDTO(Data Transfer Object)
Primary RoleAccessing the database manuallyAuto-generated database interactionData transfer between layers
PersistenceYes, interacts directly with the databaseYes, interacts with the database via Spring DataNo, not stored in the database
ImplementationRequires custom class and logicOnly interface; Spring provides implementationPlain Java class with fields
Used InLegacy/custom solutionsModern Spring Boot projectsREST APIs, controller-service communication
Annotations@Repository, @Transactional@Repository or detected by Spring automaticallyTypically none (may use Lombok annotations)
Complex LogicSuitable for custom queriesLimited; use custom repository if neededNone; 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. 

Leave a Comment