Hibernate Postgresql

Posted by dogukanhan on July 14, 2020 · 2 mins read

When you want to try hibernate functionality in Java you need a booilerplate code for setuping hibernate and postgresql connection. I have created a repository for this. The repository contains basic setup for hibernate with postgresql. You may follow this writing or you may close the repository directly.

You need to add two dependencies to your pom.xml file.

1
2
3
4
5
6
7
8
9
10
11
       <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.12</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.15.Final</version>
        </dependency>

You need to create a hibernateconfig class for generating sessionfactory from the configuration in the class. getSessionFactory method is a heavy method so make sure you don’t call it more than once. Change the conenction url, user and pass variables for your connection.

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
47
48
49
50
51
public class HibernateConfig {

    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() {

        if (sessionFactory == null) {

            try {
                Configuration configuration = new Configuration();

                Properties settings = new Properties();

                settings.put(Environment.URL, "jdbc:postgresql://localhost:5432/postgres");

                settings.put(Environment.SHOW_SQL, "true");

                settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");

                settings.put(Environment.HBM2DDL_AUTO, "create");

                settings.put(Environment.USER,"postgres");

                settings.put(Environment.PASS,"mysecretpassword");

                settings.put(Environment.DIALECT,"org.hibernate.dialect.PostgreSQLDialect");

                settings.put(Environment.PHYSICAL_NAMING_STRATEGY,NamingStrategy.class);
                configuration.setProperties(settings);

                configuration.addAnnotatedClass(Student.class);

                ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()

                        .applySettings(configuration.getProperties()).build();

                sessionFactory = configuration.buildSessionFactory(serviceRegistry);

            } catch (Exception e) {

                e.printStackTrace();

            }

        }

        return sessionFactory;

    }

}

After creating configuration class you can directyly get the sessionfactory and session so you can execute your hibernate code.

1
        Session session =   HibernateConfig.getSessionFactory().openSession();