Pages

Hibernate Utility class

In this tutorial I will write an Utility class for Hibernate that contains method to create sessionfactory, session object using best practices.

Create SessionFactory object on 1 per application and DB

Create Session object on 1 per Thread
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
Public class HBUtilty {

    private static ThreadLocal < session > threadLocal = new ThreadLocal < session > ();
    private static SessionFactory factory = null;

    static {

        factory = Configuration.configure(com / esc / conf / hibernate.cfg.xml).buildSessionFactory();

    }

    public static Session getSession() {

        Session session = null;

        if (threadLocal.get() == null) {

            session = factory.openSession()
            threadLocal.set(session);
        } else {

            session = threadLocal.get()

        }

        return session;

    }

    public static void closeSession() {

        Session session = null;
        if (threadLocal.get() != null) {

            session = threadLocal.get();
            session.close();
            threadLocal.remove();
        }

    }

    public void closeSessionFactory() {
        factory.close();
    }

}

No comments:

Post a Comment