mardi 29 mars 2016

Hibernate 4 create sessionfactory in Abstract Factory (JEE)

I'm working in a web app (JEE) with Hibernate 4.2, I have the Abstract Factory Pattern implemented but for create the session factory I have not a init method because I use the first call to create the session factory to reuse in forward like a static, like you can see I get the session from the DAOImpl, to work and finally I close it. First I want to ask if this practice it's correct? Is there another better practice?

public class HibernateSessionFactory {

    private static SessionFactory sessionFactory = buildSessionFactory();

    private static final Logger logger = LogManager.getLogger(HibernateSessionFactory.class);

    private static SessionFactory buildSessionFactory() {
        try {

            Configuration configuration = new Configuration();
            configuration.configure("hibernate.cfg.xml");

            ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            SessionFactory sf = configuration.buildSessionFactory(sr);

            return sf;

        } catch (Exception ex) {
            logger.error("Initial SessionFactory creation failed.", ex);
            ex.printStackTrace();
            throw  ex;

        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdownSessionFactory() {
        sessionFactory.close();
    }

}

DAOIMPL

public class RecordDAOImpl implements RecordDAO{.....

public String getRecord (Long id){
        Session session = HibernateSessionFactory.getSessionFactory().openSession();


        try {
            session.beginTransaction();     
            .
            .
            .

            session.getTransaction().commit();

        } catch (Exception e) {
            session.getTransaction().rollback();
        } finally {
            session.close();
        }

        return value;
    }

DAO

    public interface FieldDAO {.....

String getRecord (Long id);

Factory

public class HibernateFactoryDao extends DAOFactory {...

@Override
    public RecordDAOImpl getRecordDAO() {
        return new RecordDAOImpl();
    }

Aucun commentaire:

Enregistrer un commentaire