samedi 26 août 2017

Reducing code duplication in hibernate sessions

I am developing a REST web service using Jersey and Hibernate with Postgres for the backend. I have 3 packages for models, resources and services each. For each method in services I'm duplicating the code:

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
    transaction = session.beginTransaction();
    ***SOME UNIQUE OBJECT***  = (***SOME UNIQUE OBJECT TYPE***) session.save(***SOME UNIQUE OBJECT***);
    session.getTransaction().commit();
} catch (HibernateException e) {
    if (transaction != null) {
        transaction.rollback();
    }
} finally {
    session.close();
}
return ***SOME UNIQUE OBJECT***;

Can someone advise how I can do this without duplicating this code. I'm thinking of writing an interface for the entity model classes. Then pass that interface to the above code. Not sure if this is the best way to do this.

Aucun commentaire:

Enregistrer un commentaire