4

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.
Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
Artmal
  • 348
  • 2
  • 4
  • 16

2 Answers2

5
  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.

Optio
  • 7,244
  • 2
  • 22
  • 30
4

Most beginner tutorials on the net shows Service methods as dumb and they end up just delegating the save operation to DAO by calling the DAO save method ,as in your example of save() method. But in real world applications, atleast 50% of times you will have some business logic to write like

1) Validating the user can take some action. 2) Check a pre or post condition before data update. 3) Make sure some other data exists before saving etc.

So even though the Service method may seam analogous to DAO or Repository method, it is always useful to follow the Controller->Service->DAO workflow instead of Controller->DAO so that adding business logic to Service will be useful in future. Hope it helps.

VimalKumar
  • 1,611
  • 1
  • 14
  • 11