Artmal Artmal - 1 year ago 56
Java Question

What methods should be written in the Service Layer?

I try to follow a tutorial on Spring MVC. In the tutorial there is the UserDao interface(Spring Data JPA is used)

public interface UserDao extends JpaRepository<User, Long> {
User findByUsername(String username);

Also there is the UserService and UserServiceImpl

public interface UserService {
void save(User user);

User findByUsername(String username);

public class UserServiceImpl implements UserService {

private UserDao userDao;

private RoleDao roleDao;

private BCryptPasswordEncoder bCryptPasswordEncoder;

public void save(User user) {
Set<Role> roles = new HashSet<>();

public User findByUsername(String username) {
return userDao.findByUsername(username);

  1. Why save method is in the Service Layer and not in the dao layer? I read that all CRUD operations should go in the dao layer.

  2. What the purpose of findByUsername(String username) in UserServiceImpl? We can use the method in dao, because we use Spring Data, so Spring already implemented this functionality.

Answer Source
  1. I read that all CRUD operations should go in the dao layer.

You are right. - this is CRUD. But set password and adding the roles - it's a part of the business logic. DAO layer should know nothing about business logic. In this case dao layer should just take prepared user and save it into db. Thats all.

  1. What the purpose of findByUsername(String username) in UserServiceImpl

For the same reason, findByUsername (String username) is in the Service. This is now nothing happens and just a method is called from the DAO. But suddenly it will be necessary to add some logic before calling the method from the DAO.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download