I
I
Igor2017-07-14 15:05:11
Java
Igor, 2017-07-14 15:05:11

What is the correct approach to initializing a Hibernate session in a Java web application?

I'm starting to delve into the Hibernate library and use it in a Java web application, the servlet accepts commands and actually processes them using Hibernate.
Here is a simple and small example:

spoiler

Configuration cfg = new Configuration().configure().addAnnotatedClass(User.class);
        ServiceRegistry reg = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
        SessionFactory sf = cfg.buildSessionFactory(reg);

        Session session = sf.openSession();

        Transaction tr = session.beginTransaction();
        
        session.save(user);
        
        tr.commit();
        
        session.close();
        sf.close();



Question: should I re-initialize the Configuration, ServiceRegistry, SessionFactory with each request? If not, what is the best approach?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
AStek, 2017-07-17
@AStek

Not worth it.
And in general, it's better to read the Spring source code.
IMHO, everything is sensibly arranged there. It can be used not only as a tool but also as a guide.

I
Igor, 2017-11-15
@ApolonIn

Hello, I found the answer:
No, it's not worth it, it's enough to initialize the parameters and fariku sessions once.
It is better to initialize at the start of the application, I do this with the help of ServletContextListener

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question