简体   繁体   中英

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!

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

}

DAO provides a connection to the DataBase and operations.

The service layer provides logic to operate on the data sent to and from the DAO.

Also security - If you have service layer that has no relation to the DB it is more difficult to gain access to the DB from the client except through the service.

Service layer provides business operations and calling the DAO layer.

DAO layer is for the database layer. Meaning it performs data operations. This is where you put the retrieving of data, saving of data, and other database operations.

The answer to this question can be quite elaborate, so I will try to stick to some specifics here and will post links where ever necessary.

For some groundwork,

Layered and Tiered Architectures: You have to understand the difference between the Layers and Tiers of your application.

References:- What is the difference between tier vs layer application?

N-Tiered vs N-Layered architecture/design

So if you have three primary layers of your application: Presentation, Service, and Database, the Service Layer is the one where service classes are kept. This is a place to add the core business logic to your application. Eg If you are developing a Ticketing Application using three layers, and you have a comprehensive Authentication functionality added to it then.

  1. The web pages will be a part of the presentation layer.
  2. The functionality like validation of the user-id, encryption check, timeout check etc will be a part of your service layer (Service Classes)
  3. The connections to the DB and the respective interactions will be taken care of in the database layer (Hibernate)

Additionally: The application architectures are not simply confined to three layered systems nowadays. There is an increased adoption of distributed application architectures where the Service Layer mentioned in point 2 above, is broken into multiple small services, each with their own database. (Keyword check: Microservices ). Also, they interact using messaging queues, but talking of all those things is not relevant to this question.

Recommended: 1. You go through the articles on the designing of service layers, and how different requirements lead to a different design of the Service Classes. 2. You read about design patterns like Providers, Factories, Singletons etc. which are commonly used in the designing of Services.

I hope I have answered your question.

NB: You need to tag your question with 'architecture' as it is more a question of Architecture than Java programming.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM