1

i have a problem with my hibernate query SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); sess =sessionFactory.openSession(); i call it in every function ,how can i avoid it an create sessionFactory only once

1 Answer 1

0

You simply create instance once per application, store reference and provide method to access it. What is right way and place to do this depends perfectly about your application.

This is one way:

public final class SessionFactoryProvider {
    private static final SessionFactory sessionFactory;
    static {
        sessionFactory = new Configuration().configure().buildSessionFactory();
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    private SessionFactoryProvider() {
    }
}

Additionally it can be that you want to add some extra information collection and catching and re-throwing possible exception from static initializer block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.