Why put a DAO layer over a persistence layer (like JDO or Hibernate)

前端 未结 10 826
梦谈多话
梦谈多话 2021-01-31 09:13

Data Access Objects (DAOs) are a common design pattern, and recommended by Sun. But the earliest examples of Java DAOs interacted directly with relational databases -- they were

10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-31 09:18

    If you use an ORM: Enjoy their Transparent Persistence Support! Don't use DAOs to wrap ORM APIs. As it was well said here, DAOs are before ORMs. ORMs has introduced concepts from OODBMS, like Transparent Persistence and Persistence by Reachability. You have to take advantage of that, because it will make your life easier and your code beautiful. Suppose your are modeling departments and employees... One use case might be creating a new department, creating a new employee and adding the employee to the department... what you would do the?

    //start persistence context
    ...
    Department dept1 = new Department("department1");
    dept1.addEmployee(new Employee("José", 10503f));
    
    em.persist(dept1);
    ...
    //close persistence context
    

    Department, Employee and their relation are persistent now.

    Suppose now you have to add an existing Employee to and existing Department... what you would do? pretty simple:

    //start persistence context
    ...
    Department aDepart = hibernateSession.load(Department.class, dId);
    Employee anEmployee = hibernateSession.load(Employee.class, eId);
    
    aDepart.addEmployee(anEmployee);     
    ...
    //close persistence context
    

    Pretty simple thanks to the Transparent Persistence and Persistence by Reachability that Hibernate (like other ORMs) implements. No DAOs at all.

    Just code your domain model and think like you are persisting in memory. With a good mapping strategy, the ORM will transparently persist what do you in memory.

    More examples here: http://www.copypasteisforword.com/notes/hibernate-transparent-persistence http://www.copypasteisforword.com/notes/hibernate-transparent-persistence-ii

提交回复
热议问题