Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public void save(User user) {
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        Set<Role> roles = new HashSet<>();
        roles.add(roleDao.getOne(1L));
        user.setRoles(roles);
        userDao.save(user);
    }

    @Override
    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.
like image 841
Artmal Avatar asked Feb 05 '23 21:02

Artmal


1 Answers

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

You are right. userDao.save(user) - 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.

like image 56
Optio Avatar answered Feb 07 '23 17:02

Optio