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