简体   繁体   中英

Advice about using DAO/Spring MVC/Hibernate

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 ie

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(ie non existing record or database failed) if any.

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

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 )

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 RuntimeException s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM