0

I see some Spring-MVC projects which have EntityDAO, EntityDAOImpl and EntityService. I don't understand what's the different between them. For example, I have a user entity.

public Class UserEntity {
    private int userId;
    private String userName;
    private String userInfo;
    // getter and setter
}

The UserDAO:

@Repository
public interface UserDAO {
    @Select({"SELECT * FROM user WHERE id=#{id};"})
    UserEntity getById(final int id);
}

The UserDAOImpl:

@Repository
public class UserDAOImpl implements UserDAO {
    @Autowired
    private UserDAO userDAO;

    @Override
    public UserEntity getById(int id) {
        return userDAO.getById(id);
    }
}

The UserService:

@Service
public class UserService {
    @Autowired
    private UserDAOImpl UserDAO;

    public UserEntity getById(int id) {
        return userDAO.getByid(id);
    }
}

So, I think using UserDAOImpl is enough, why should I need UserService?

Skyler Tao
  • 33
  • 1
  • 8

1 Answers1

0

The service layer is a software engineering pattern that tries to decouple the existing code dependencies and aims on making highly cohesive code layers, making each class have a single responsibility. This answer on SO and this other answer in SE provide some details about the MVCS (Model View Controller Service) pattern and it can apply to your question too.

In this scenario, the UserDao interface would have an implementation in UserDaoImpl because it is much easier (and better) to build a loosely-coupled system through the usage of interfaces (a great reading on this can be found here).

The UserService class provides many different methods that operate on a UserEntity object. In this case, the service would make use of the DAO to perform any database-related operation, but could also be used to provide other functionalities that go beyond the scope of a DAO class.

In a nutshell: the DAO should only perform operations that regard a connection to the database. Any other thing that you want to do with the results retrieved from your DB would under be responsibility of the service.

It is common to segregate these layers in a way that Services expose methods that perform additional operations on top of the entity (or entities) provided by simpler interfaces, such as DAOs. For example, if you need to parse the results or perform any reduction operation on top of it, that is not a DAO responsibility, hence it would be assigned to the service.

Another great reading that goes beyond my explanation and provides an excellent level of detail on this subject is Service layer vs DAO — Why both?, on the Software Engineering Stack Exchange.

Community
  • 1
  • 1
Bruno Toffolo
  • 1,504
  • 19
  • 24