我已经阅读了有关DAO类和Service类的信息,但我不了解它们的用途。
我已经在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>


控制器登录的方法是这样的:

@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")


公共类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);
}


和loginDAOimpl:

@Repository("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;
}


那么,我应该在服务类和DAO类中写什么?
我了解的是,用于处理数据库中数据的代码需要保留在DAO类中,但是服务类却适用于什么?
谢谢!

最佳答案

您可以参考以下简单示例:

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

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

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

}

关于java - 有关如何使用DAO类和Service类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41585560/

10-11 23:21