Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic DAO hibernate 4 + spring 4 and exception handling

I'm working on a spring mvc project lately, and i'm new to hibernate and spring.

the thing is , i want to save my self from copying the code over and over, at least save myself from the crud operations. So an exemple on how to make a generic interface and then an implementation would really help.

I searched the internet first, and i found some recommendations on using SessionFactory (i have the bean already thanks to spring), and also recommendations on using the transaction manager (don't really get how to, even though, i would like to add some @Transactional annotations)

And also, a really important matter, i would like to know which exceptions should i handle ?

like image 842
Aissasa Avatar asked Aug 24 '14 22:08

Aissasa


1 Answers

Generally you go by making a generic DAO interface (could be called as a CRUD repository) and making this generic. Example (Please note that this is not that verbose, just for referring):

public interface GenericDAO<T, ID extends Serializable> {
    T save(T entity);
    void delete(T entity);
    }

Example implementation:

    public class GenericHibernateDAO<T, ID extends Serializable>
            implements GenericDAO<T, ID> {
        private Class<T> persistentClass;

        public GenericHibernateDAO() {
            this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
                    .getGenericSuperclass()).getActualTypeArguments()[0];
        }

        private SessionFactory sessionFactory;

        public void setSessionFactory(SessionFactory sessionFactory) {
            this.sessionFactory = sessionFactory;
        }

         public Session getSession()
        {
             return sessionFactory.getCurrentSession();
        }

        @Override
        public T save(T entity)
        {
            getSession().save(entity);
            return entity;
        }
        @Override
        public void delete(T entity) {
            getSession().delete(entity);        
        }
}

Also, you can refer other similar SO question.

For exception handling you can handle business exceptions or for that matter any exception at individual controller level or from a single point using @ControllerAdvice. E.g:

@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    @ExceptionHandler(Exception.class)
    public String exception(Exception e) {

        return "error";
    }
}

Here is a good blog which touches on exception handling at individual controller level using @ExceptionHandler and at global level using @ControllerAdvice as well as @ExceptionHandler

----------------------------------UPDATE------------------------------------

Hibernate throws a runtime exception called HibernateException. Think of @Transactional as your BEGIN TRANSACTION COMMIT ROLLBACK model in database, i.e. if you do any operations inside a transaction and if any error occurs during this you should rollback the entire transaction. So, generally we put this sort of code/annotation (@Transactional) in the service layers where you may combine several dao methods and put them together in a transaction making them as a unit of work.

The syntax for using this is:

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)

What this means is that if any exception occurs (please note that I have explicitly mentioned Exception.class you can increase the scope and make it Throwable.class) spring would rollback any data updated/ inserted/ deleted for you. If you want to understand Propagation please refer this.

like image 169
Sandeep B Avatar answered Oct 31 '22 12:10

Sandeep B