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);
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With