jeudi 24 septembre 2015

Accessing hibernate objects in a servlet from a DAO

I have created a DAO like this: This is based from: Hibernate: CRUD generic DAO

public class Dao{
    SessionFactory sessionFactory;
    // initialise session factory
    public User save(User o){
        return (User) sessionFactory.getCurrentSession().save(o);
    }

    public User get(Long id){
        return (User) sessionFactory.getCurrentSession().get(User.class, id);
    }

    public User void saveOrUpdate(User o){
                    sessionFactory.getCurrentSession().saveOrUpdate(o);
    }

Now, this is all fine, if my sessionFactory is in the DAO or in other classes. But my problem is calling SessionFactory from the servletContextListener: Here is my code in the listener:

public void contextInitialized(ServletContextEvent event)  {
    StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
    try {
        sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        event.getServletContext().setAttribute("factory", sessionFactory);
    } catch(Exception e) {
        e.printStackTrace();
        StandardServiceRegistryBuilder.destroy( registry );
    }
}

How would I call SessionFactory from the DAO in this case?

Aucun commentaire:

Enregistrer un commentaire