Search code examples
javaspringhibernatedaoservice-layer

For what to use DAO classes and Service classes


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!


Solution

  • You can refer to this simple example:

    1.PersonDao only cares about database operation.

    package com.pechen.dao;
    
    import java.util.List;
    
    import com.pechen.entity.Person;
    
    public interface PersonDao {
    
        public void save(Person p);
    
        public List<Person> list();
    
    }
    

    2.PersonDaoImpl is the implementation.

    package com.pechen.dao;
    
    import java.util.List;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.springframework.beans.factory.annotation.Autowired;
    
    import com.pechen.entity.Person;
    
    public class PersonDaoImpl implements PersonDao {
    
        @Autowired
        private SessionFactory sessionFactory;
    
        public void setSessionFactory(SessionFactory sessionFactory) {
            this.sessionFactory = sessionFactory;
        }
    
        public void save(Person p) {
            Session session = sessionFactory.openSession();
            Transaction tx = session.beginTransaction();
            session.save(p);
            tx.commit();
            session.close();
        }
    
        @SuppressWarnings("unchecked")
        public List<Person> list() {
            Session session = sessionFactory.openSession();
            List<Person> rst = session.createQuery("from person").getResultList();
            session.close();
            return rst;
        }
    
    }
    

    3. PersonService cares about the business logic, you can do anything you want before the database operation.

    package com.pechen.service;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    
    import com.pechen.dao.PersonDao;
    import com.pechen.dao.PersonDaoImpl;
    import com.pechen.entity.Person;
    
    public class PersonService {
    
        @Autowired
        private PersonDao personDao;
    
        public void setPersonDao(PersonDaoImpl personImpl) {
            this.personDao = personImpl;
        }
    
        public void savePerson(Person person) {
            // other business logic
            this.personDao.save(person);
            System.out.println("Save person successfully: " + person);
        }
    
        public List<Person> getPersons() {
            // other business logic
            return this.personDao.list();
        }
    
    }