简体   繁体   English

有关如何使用DAO类和Service类

[英]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. 我已经阅读了有关DAO类和Service类的信息,但我不了解它们的用途。 I have started a project in maven with spring and hibernate, and until now I have added in servlet.xml the configs for hibernate: 我已经在Spring和Hibernate的Maven中启动了一个项目,直到现在我在servlet.xml中添加了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: loginServiceImpl:

@Service("loginService")

public class LoginServiceImpl implements LoginService { 公共类LoginServiceImpl实现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: 和loginDAOimpl:

@Repository("loginDAO")

public class LoginDAOImpl implements LoginDAO { 公共类LoginDAOImpl实现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? 那么,我应该在服务类和DAO类中写什么? What i understand is that the code for manipulating data from database needs to stay in DAO classes, but services classes are for what? 我所了解的是,用于处理数据库数据的代码需要保留在DAO类中,但是服务类却有什么用? Thanks! 谢谢!

You can refer to this simple example: 您可以参考以下简单示例:

1. PersonDao only cares about database operation. 1. PersonDao只关心数据库操作。

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. 2. PersonDaoImpl是实现。

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. 3. PersonService关心业务逻辑,您可以在数据库操作之前做任何想做的事情。

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. DAO提供到数据库和操作的连接。

The service layer provides logic to operate on the data sent to and from the DAO. 服务层提供逻辑以对发送到DAO和从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层。

DAO layer is for the database layer. DAO层用于数据库层。 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 N层与N层架构/设计

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) 诸如验证用户ID,加密检查,超时检查等功能将成为您的服务层(服务类)的一部分
  3. The connections to the DB and the respective interactions will be taken care of in the database layer (Hibernate) 与数据库的连接以及各个交互将在数据库层(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. 分布式应用程序体系结构已得到越来越多的采用,其中上面第2点提到的服务层分为多个小型服务,每个服务都有自己的数据库。 (Keyword check: Microservices ). (关键字检查: 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. 推荐:1.您将阅读有关服务层设计的文章,以及不同的需求如何导致服务类的不同设计。 2. You read about design patterns like Providers, Factories, Singletons etc. which are commonly used in the designing of Services. 2.您了解了服务设计中通常使用的设计模式,例如提供者,工厂,单身人士等。

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. 注意:您需要用“体系结构”标记问题,因为它比Java编程更多的是体系结构问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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