Skip to content

Basic configuration

In order to be able to use the Hibernate framework in an application, we need to create some configuration files. One of the most important components is the hibernate.cfg.xml file, which is e.g. responsible for database connection configuration and contains information about classes, which represent tables in the database.

A sample configuration may look like this:

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/sda</property>
        <property name="connection.username">root</property>
        <property name="connection.password">my-secret-pw</property>
        <property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
    </session-factory>
</hibernate-configuration>

In practice, this configuration is often more complicated, but the example above shows the minimum information that Hibernate needs.

SessionFactory

Thanks to the above configuration file, we are able to create a SessionFactory object, thanks to which we will create a Session object, which is needed to perform any operations on the database. In order to create the SessionFactory object we use theConfiguration object, e.g.:

SessionFactory sessionFactory = new Configuration()
   .configure("hibernate.cfg.xml")
   .buildSessionFactory();

Session

Thanks to the SessionFactory object, we create a Session object that can directly perform database operations. According to the intention, this object should be created each time it is necessary to perform a database operation (one or more). After their execution, the session should be closed.

NOTE: The Session object implements the AutoCloseable interface, so we can create sessions using try-with-resource.

NOTE: The Session object implements the EntityManager interface which enables entity management.