I have read about DAO classes and Service classes but I don't understand for what are they used. I have started a project in maven with spring and hibernate, and until now I have added in servlet.xml the configs for hibernate:
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.fabbydesign.model.Useradmin</value>
</list>
</property>
</bean>
The method from controller for login is like this:
@RequestMapping(value = "/do.html", method = RequestMethod.POST)
public String doLogin(@Valid @ModelAttribute("userLogin") LoginForm lf, BindingResult bindingResult, Map<String, Object> model, HttpServletRequest request){
//bindingResult.rejectValue("username", "label.title"); - to add new message error
logger.trace("showLogin - post");
//check fields if the filds are filled and respects the size from beans
if(bindingResult.hasErrors())
return "login";
boolean userExists = loginService.checkLogin(lf.getUsername(), lf.getPassword());
if(!userExists){
bindingResult.rejectValue("username", "login.username.wrongUserOrPassword");
return "login";
}
else{//set session
request.getSession().setAttribute(adminSesName, true);
}
return "redirect:/admin/dashboard.html";
}
loginServiceImpl:
@Service("loginService")
public class LoginServiceImpl implements LoginService {
@Autowired
private LoginDAO loginDAO;
public void setLoginDAO(LoginDAO loginDAO) {
this.loginDAO = loginDAO;
}
public Boolean checkLogin(String userName, String userPassword) {
return loginDAO.checkLogin(userName, userPassword);
}
and loginDAOimpl:
@Repository("loginDAO")
public class LoginDAOImpl implements LoginDAO {
@Resource(name = "sessionFactory")
protected SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected Session getSession() {
return sessionFactory.openSession();
}
final static Logger logger = Logger.getLogger(LoginDAOImpl.class);
public boolean checkLogin(String username, String password) {
Boolean userFound = false;
Session session = sessionFactory.openSession();
String sql = "from Useradmin where username = ?";
Query<?> query = session.createQuery(sql);
query.setParameter(0, username);
List<?> list = query.list();
if ((list != null) && (list.size() == 1)) {
Useradmin ua = (Useradmin) list.get(0);
if (BCrypt.checkpw(password, ua.getPassword())) {
userFound = true;
}
}
return userFound;
}
So, what i should write in service classes and in DAO classes? What i understand is that the code for manipulating data from database needs to stay in DAO classes, but services classes are for what? Thanks!