Junior — Middle
Can you explain the DAO concept in Spring and its role in application architecture?
sobes.tech AI
Answer from AI
DAO (Data Access Object) is a design pattern that separates data access logic from the business logic of the application.
In Spring, DAO is usually implemented as a component responsible for interacting with the database or other data storage. It encapsulates CRUD operations (create, read, update, delete) and hides the details of access implementation (e.g., JDBC, JPA, Hibernate).
The role of DAO in architecture:
- Data access isolation: the business layer does not depend on specific storage technologies.
- Simplified testing: DAO can be easily mocked during tests.
- Improved code readability and maintainability: clear separation of responsibilities.
Example of DAO in Spring using JPA:
@Repository
public class UserDao {
@PersistenceContext
private EntityManager em;
public User findById(Long id) {
return em.find(User.class, id);
}
public void save(User user) {
em.persist(user);
}
public void update(User user) {
em.merge(user);
}
public void delete(User user) {
em.remove(user);
}
}
Thus, DAO acts as a layer between business logic and data source, ensuring a clean and maintainable architecture.