Spring + Hibernate 访问数据怎么就这么复杂

发布时间: 2017-05-17 17:34:23 作者: 大象笔记

又是 DAO 层,又是 Service 层。每层还都加上一个 interface。我只是要实现一个拉取所有数据的操作。搞这么多层有什么用?

DAO 是什么?

Data Access Object 是一个 object 或者 interface 用于访问数据库或者其他持久化储存系统。

例如,我们有一个 Entity 来描述一个 Person

public class Person {

    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

而 Person 的信息需要持久化到数据库中,这时我们就需要一个对应的 DAO object 或者 interface 来建立 Person Entity 与数据库的联系。

例如,这里先定义一个 DAO interface

interface PersonDAO {

    List<Person> findAll();
    List<Person> findById();
    List<Person> findByName();
    boolean insertPerson(Person person);
    boolean updatePerson(Person person);
    boolean deletePerson(Person person);

}

然后按照这个 interface 实现一个具体的 implementation,或者几个 implementations。例如,一个关联数据库,一个关联文本文件。

DAO 层一定要有个 interface?

如果你100%确定只需要关联特定数据库,例如 MySQL,那么这个 interface 就有些多余了,直接写实现就好。

Service 又是什么?

Service 主要用来写业务逻辑,例如,当业务逻辑比数据逻辑复杂的多的时候,就需要 Service 层来做分离

@Transactional
public class PeopleService {

    private PeopleDAO pDAO;
    private CityDAO cDAO;

    public void createPerson(String name, String city)
     throws PeopleServiceException {
        Person p = new Person();
        p.setName(name);

        City c = cDAO.getCityByName(city);
        if (c == null) throw new ServiceException(city + " doesn't exist!");
        if (c.isFull()) throw new ServiceException(city + " is full!");
        c.addPeople(p);

        sess().save(p);
        sess().save(c);
    }

}

当然是否需要 interface 取决于跟 DAO 一样的问题。

DAO 与 Service 是 Spring 引入的概念?还是 Hibernate 引入的?

是 Spring 引入的。

Hibernate 用来作为某一 DAO interface 的实现。例如:

interface PersonDao {
}
	
class HibernatePersonDao implements PersonDao {
}

class LdapPersonDao implements PersonDao {
} 

参考

我是一名山东烟台的开发者,联系作者