5

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 ?

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
Aissasa
  • 231
  • 5
  • 18
  • for [exceptions](http://ankursinghal86.blogspot.in/2014/07/exception-handling-in-spring-mvc.html) – Ankur Singhal Aug 25 '14 at 03:30
  • 1
    Tip, ditch plain hibernate use JPA and use [Spring Data JPA](http://projects.spring.io/spring-data-jpa/), that will save you from writing even the repositories. – M. Deinum Aug 25 '14 at 05:41
  • M.Deinum , that's interesting, my question is, does that mean that i won't use hibernate? and what are the advantages of Spring Data JPA over hibernate ? – Aissasa Aug 25 '14 at 10:53

1 Answers1

6

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.

Community
  • 1
  • 1
Sandeep B
  • 765
  • 1
  • 6
  • 19
  • thanks for the clear response, but the thing that you didn't answer me about is what type of exceptions are thrown when using hibernate, and how to use the annotation transactional ? – Aissasa Aug 25 '14 at 10:31