开发者

DAO vs ORM(hibernate) pattern [closed]

Closed. This question is opinion-based. It is not currently accepting answers.

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 9 years ago.

Improve this question

i read in some articles DAO is not mandatory with hibernate and its implementation is by "it depends", in other words, we can choose between ORM vs DAO pattern.

Ok, let's assume that i don't want use a DAO pattern, so im using only session CRUD and query operation provided by hibernate(my ORM).

Especially for the "search" and "find" queries is not correct to rewrite them always, so is reasonable think to put them into a class.

But then this class is a simple DAO without all implementation of DAO pattern and DAOFactory, only a lightweight implementation of a DAO. So, the point is that we need alway a DAO and the choice is heavy DAO implementation vs lightweight DAO implementation?

What i said is wrong?

EDIT Another problem i have is where put dao interactions, for example i have to login a User and write a Log of the login (useless example i know...)

So in a DAO pattern i have all generic dao implementations, a DAOFactory and finally UserHibernateDAO and LogHibernateDAO. The login operation is a business method:

private void login(String username, String password){
    daoFactory.beginTransaction();
    UserDAO userDao=daoFactory.HIBERNATE.getUserDao();
    LogDAO logDao=daoFactory.HIBERNATE.getLo开发者_JS百科gDao();
    if(userDao.checkAccount(username, password){
        User user=userDao.findByAccount(username, password);
        logDao.save(new Log("log-in", user);
    }
    daoFactory.commit();
}

Is this reasonable? Can i use dao in this way? If i want handle exception, the better place to do it is ina a business logic?

EDIT2 Let's assume to use a DAO pattern, the main reason to do it is to be able to switch between tecnhology(ORM->JDBC etc..), it all fine and ok, BUT where can i handle hibernate session and transaction? I can't put it into a DAO, it's anty pattern, and i can't put it into a service layer, becouse in a hipohtetycal switch i have to remove all this transaction(becouse other tecnhology may not use them).


ORM and DAO are orthogonal concepts. One has to do with how objects are mapped to database tables, the other is a design pattern for writing objects that access data. You don't choose 'between' them. You can have ORM and DAO is the same application, just as you don't need ORM to use the DAO pattern.

That said, while you never really need anything, you should use DAOs. The pattern lends itself to modularized code. You keep all your persistence logic in one place (separation of concerns, fight leaky abstractions). You allow yourself to test data access separately from the rest of the application. And you allow yourself to test the rest of the application isolated from data access (i.e. you can mock your DAOs).

Plus, following the DAO pattern is easy, even if implementing data access can be difficult. So it costs you very little (or nothing) and you gain a lot.

EDIT -- With respect to your example, your login method should be in some sort of AuthenticationService. You can handle exceptions there (in the login method). If you used Spring, it could manage a bunch of things for you: (1) transactions, (2) dependency injection. You would not need to write your own transactions or dao factories, you could just define transaction boundaries around your service methods, and define your DAO implementations as beans and then wire them into your service.

EDIT2

The main reason to use the pattern is to separate concerns. That means that all your persistence code is in one place. A side effect of this is, test-ability and maintainability, and the fact that this makes it easier to switch implementations later. If you are building Hibernate based DAOs, you can absolutely manipulate the session in the DAO, that is what you are supposed to do. The anti pattern is when persistence related code happens outside of the persistence layer (law of leaky abstractions).

Transactions are a bit trickier. At first glance, transactions might seem to be a concern of persistence, and they are. But they are not only a concern of persistence. Transactions are also a concern of your services, in that your service methods should define a 'unit of work', which means, everything that happens in a service method should be atomic. If you use hibernate transactions, then you are going to have to write hibernate transaction code outside of your DAOs, to define transaction boundaries around services that use many DAO methods.

But note that the transactions can be independent of your implementation -- you need transactions whether or not you use hibernate. Also note that you don't need to use the hibernate transaction machinery -- you can use container based transactions, JTA transactions, etc.

No doubt that if you don't use Spring or something similar, transactions are going to be a pain. I highly recommend using Spring to manage your transactions, or the EJB spec where I believe you can define transactions around your services with annotations.

Check out the following links, for container based transactions.

Container-Managed Transactions

Sessions And Transactions

What I am gathering from this is that you can easily define the transactions outside the DAOs at the service level, and you don't need to write any transaction code.

Another (less elegant) alternative is to put all atomic units of work within DAOs. You could have CRUD DAOs for the simple operations, and then more complicated DAOs that do more than one CRUD operations. This way, your programmatic transactions stay in the DAO, and your services would call the more complicated DAOs, and wouldn't have to worry about the transactions.

The following link is a good example of how the DAO pattern can help you simplify code

AO vs ORM(hibernate) pattern

(thanx @daff)

Notice how the definition of the interface makes it so that you business logic only cares about the behavior of the UserDao. It doesn't care about the implementation. You could write a DAO using hibernate, or just JDBC. So you can change your data access implementation without affecting the rest of your program.


Let me provide a source code example to hvgotcodes good answer:

public class Application
{
    private UserDao userDao;

    public Application(UserDao dao)
    {
        // Get the actual implementation
        // e.g. through dependency injection
        this.userDao = dao;
    }

    public void login()
    {
        // No matter from where
        User = userDao.findByUsername("Dummy");
    }
}


public interface UserDao
{
    User findByUsername(String name);
}

public class HibernateUserDao implements UserDao
{
    public User findByUsername(String name)
    {
        // Do some Hibernate specific stuff
        this.session.createQuery...
    }
}

public class SqlUserDao implements UserDao
{
    public User findByUsername(String name)
    {
        String query = "SELECT * FROM users WHERE name = '" + name + "'";
        // Execute SQL query and do mapping to the object
    }
}

public class LdapUserDao implements UserDao
{
    public User findByUsername(String name)
    {
        // Get this from LDAP directory
    }
}

public class NoSqlUserDao implements UserDao
{
    public User findByUsername(String name)
    {
        // Do something with e.g. couchdb
        ViewResults resultAdHoc = db.adhoc("function (doc) { if (doc.name=='" + name + "') { return doc; }}");
        // Map the result document to user
    }
}

So, as already mentioned, DAO is a design pattern to minimize coupling between your application and you backend whereas ORM deals with how to map objects into an object-relational database (which reduces coupling between the database and you application, but in the end, without using a DAO your application would be dependend on the ORM used or on a higher level a standard like JPA).

Therefore, without DAOs, it would be really hard to change your application (e.g. moving to a NoSQL database instead of a JPA compatible ORM).


No, I don't think that's correct. ORM is one way to implement DAO; you can choose to do DAO without ORM.

You've got it backwards: I'd consider ORM to be heavier than DAO, because the dependencies are greater. I can write a DAO in straight JDBC without ORM. That's lighter, IMO.

Whether or not we agree depends on how we define "light" and "heavy". I'm going by dependencies - the number of extra JARs required over above the JDK itself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜