1

I'm trying to get the clear picture of how this works:

-What is the advantage of using DAO class with DAO interface?
-How to handle Hibernate exceptions i.e

public String doSomething(){
    Session session = sessionFactory.getCurrentSession();
    session.beginTransaction();

      Query query = session.createQuery("");

    Object o = query.uniqueResult();

    session.close();

    return "success";
}

I'm not "forced" to try/catch, so how do I catch/intercept any exceptions that may occur?

-Is opening session everytime for new DAO method more expensive than getting the current session? Should I close the session if I use get?

Question Update:

I have @Service annotation in my service classes and for each method using dao interface I've got @Transactional above. Also I've added @Repository to all my DAO classes

Update II:

I'm considering opening bounty for this questions because I want to know more details and this time I'll provide some.

  1. Spring context
  2. Controller
  3. Service Interface
  4. Service Implementation
  5. DAO interface
  6. DAO implementation

So I want to utilize spring MVC as much as possible, how do I make session opening/closing handled by @Transactional?

How do I catch the exceptions(i.e. non existing record or database failed) if any.

What I'm doing wrong? Can anyone suggest some improvements?

Cœur
  • 37,241
  • 25
  • 195
  • 267
London
  • 14,986
  • 35
  • 106
  • 147
  • Regarding your update... do the annotations help or are they not working? – Michael J. Lee Jul 14 '11 at 01:04
  • @Michael J. Lee thanks for your response, it became very popular, I've updated question with more details – London Jul 14 '11 at 20:36
  • I'd love to answer but, i would suggest opening another question. My answer is becoming pretty long. – Michael J. Lee Jul 15 '11 at 13:27
  • @Michael J. Lee and so I did open another question http://stackoverflow.com/questions/6709750/proper-usage-of-spring-mvc-3-with-hibernate-spring-orm and accepted the answer. thanks – London Jul 15 '11 at 15:50

2 Answers2

7

A few things on the hibernate session side...

1.) I would take a look a integrating Spring's transaction management into your project. This way you don't have to worry about opening and closing your session's because Spring will handle this for you with intercepts using the @Transactional annotation.

2.) If spring is handling your transactions you won't have to worry about doing the finally calls to make sure everything is closed or rolled back.

3.) If you decide not to use Spring to manage the sessions you should not keep it open for any extended period of time but again, if you use Spring you don't have to worry about it.

As far as the interface on the DAO classes i offer this...

1.) It is considered a good design practice to code to interfaces (see comments left below) and here are a few good reasons why.

lets say you have a...

public interface ShoppingCartService{

    public void doStuff(Object obj);

} 

You could expose this service as a servlet and deal with the just the 'contract' your interface creates or even hide the fact your using Hibnerate, JDBC or anything else...

@Service
public class PetShopShoppingCartService implements ShoppingCartService{

    @Transactional(propagation=Propagation.REQUIRED)
    public void doStuff(Object obj){
        //The Pet Shop service impl uses hibernate!;
    }
}

or...

public class DrugStoreShoppingCartService implements ShoppingCartService{

    public void doStuff(Object obj){
        //The Drug Store service uses JDBC;
    }
}

Or even...

public class NextBigThingShoppingCartService implements ShoppingCartService{

    public void doStuff(Object obj){
        //do stuff with next big thing;
    }
}

I think you get the picture. If you developing public api's or exposing services this becomes pretty important.

Lastly, another good reason to have the interfaces is with working in a team of more than a couple developers. You can quickly stub out an interface, check-in and tell everyone else that this is how it's going to look. This allows them to see what's important and even mock their own impl if they need to (ThingServiceMockDataImpl)

Michael J. Lee
  • 12,278
  • 3
  • 23
  • 39
  • 2
    100% agree with Michael's assessment. As to the interface question, it's considered good practice to code to interfaces, allowing an interface to express a contract and a class to fulfill the contract. There are other, more practical reasons, such as to allow dynamic proxying, but that's probably the best one. – Ryan Stewart Jul 13 '11 at 20:47
  • @Michael J. Lee hi Michael I've updated my question, what details than I'm missing, if spring is not doing those things for me? – London Jul 13 '11 at 21:05
  • 1
    I believe that aspect-oriented transactions require an interface to generate the proxy. +1 for Michael J. Lee's good answer. – duffymo Jul 13 '11 at 23:46
  • 1
    @duffymo: actually, Spring can now use cglib to do its aspect-related proxying, so interfaces are no longer strictly required, but they're no less essential for fluid, well-designed apps. – Ryan Stewart Jul 14 '11 at 01:05
0

Just because you're not forced to catch exceptions when using Spring's HibernateTemplate doesn't mean that they will not get thrown. They will just be RuntimeExceptions instead of checked exceptions. Also, getCurrentSession() does not open a new session each time you call it, it returns the local Thread's Session.

There are lots of advantages, including lack of code coupling, encapsulation, and transaction demarcation for using the DAO strategy instead of putting your data access code directly into your controller. See http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html for more info.

Abdullah Jibaly
  • 53,220
  • 42
  • 124
  • 197