views:

195

answers:

3

Hi all, 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 an 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.getLogDao();
    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).

+2  A: 

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.

duffymo
+10  A: 

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, testability 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.

http://download.oracle.com/javaee/5/tutorial/doc/bncij.html http://community.jboss.org/wiki/sessionsandtransactions

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

http://stackoverflow.com/questions/4037251/we-really-need-a-dao-for-our-hibernate-application/4037454#4037454

(thanx @daff)

Notice how the definition of the interace 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.

hvgotcodes
@hvgotcodes: ok but if i choice to don't use DAO pattern, how i have to proceed? in other words, with hibernate and WITHOUT DAO, where i put my entity CRUD logic and HQL queies or criteria queries etc... ?
blow
@blow, thats the entire point. You have to put the persistence code somewhere. And you should keep it separated from the business logic of your app. So why not put it in a DAO? In other words, you are going to write a DAO, the question is, are you going to follow the pattern.
hvgotcodes
@hvgotcodes: thank you for explanation, at the moment i don't want to use spring to manage DAO, first i want know how DAO pattern work and if i really need it.PS. i have another small doubt, i've edited first question.
blow
@blow -- i updated my answer for your second edit. Others, this is outside my wheelhouse, so comments are definitely welcome on how to handle the transactions....
hvgotcodes
+4  A: 

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).

Daff
@Daff: thank Daff your example is very clear. you say "without using a DAO your application would be dependend on the ORM used or on a higher level a standard like JPA", ok, but i need to write a simple DAO anyway, i can call with other name like UserService or UserManager or UserSessionfacade, but it is a simple DAO... So, the real choice is between a real implementation of a DAO with some benefits, or a simple hibernate DAO that incapsule all my CRUD operation or queries for a certain entity.
blow
@daff good and simple example...
hvgotcodes
THanks. @blow: If you are using a service based application approach you might see your services as the DAO and if you don't need another level of abstraction you imho don't need the DAOs in between. In bigger applications I usually let the services handle session and transaction management and redirect the actual work to the DAOs. But that depends.
Daff