Topic 2 – Configuring Hibernate Configuration File

image 2

Play Store Application link – Hibernate – in 10 steps – Apps on Google Play

Configuring Hibernate is the process of setting up the framework to connect to a database, define mapping files and specify the persistent objects that will be used in the application.

There are following steps to perform-
1- Importing Hibernate libraries (Classes/Interfaces)
2- Creating Hibernate Configuration File

Step 1-

  • Add Hibernate libraries to your project
  • Libraries can be found on the Hibernate website
  • Libraries needed: core Hibernate framework, Hibernate annotations, and database driver

Here is an example of how to add the necessary libraries to a project using Maven:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.3.5.Final</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-annotations</artifactId>
    <version>3.5.6-Final</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.24</version>
</dependency>

-> Group ID (groupId): It’s like a company or organization name that groups related projects together. Example: org.hibernate means it belongs to the Hibernate organization.

->Artifact ID (artifactId): It’s the specific project or library name within that group. Example: hibernate-core means it is the core Hibernate library.

Note – There are several alternative ways to import dependencies without using a pom.xml file:

  1. You can manually download the JAR files for the dependencies and add them to the classpath of your project.
  2. You can use the Gradle or Apache Ivy build tools, which do not require a pom.xml file. Instead, you can specify dependencies in a build.gradle or ivy.xml file.
  3. You can use a package manager such as Maven Wrapper, SDKMAN or Jabba that can download the dependencies and manage them for you, without the need for a pom.xml file.
  4. You can use a build tool like Apache Ant which uses build.xml file instead of pom.xml to manage dependencies.
  5. Some IDEs like Eclipse and IntelliJ IDEA also have support for adding dependencies to a project without using a pom.xml file.

Important-

Hibernate Interfaces/ClassDescription
Configuration classUsed to configure Hibernate settings and create a SessionFactory
Session InterfaceRepresents a single unit of work with the database, used for creating, reading, updating, and deleting objects, and committing or rolling back a transaction
SessionFactory InterfaceFactory for creating Session objects, thread-safe and can be used to create multiple sessions
Transaction InterfaceRepresents a unit of work with the database, used to group multiple operations together and commit or rollback all of them at once
Query InterfaceUsed to execute HQL (Hibernate Query Language) and native SQL queries, can be used to retrieve, update, or delete data
Criteria InterfaceUsed to create type-safe and type-sensitive queries, can be used to retrieve data based on certain criteria, retrieve specific fields, or retrieve data based on certain conditions

Step 2- Next,

  • Create a configuration file named “hibernate.cfg.xml” put it in resources folder
  • Include connection details for the database
  • Information to include: database URL, username, password, SQL dialect

Here is an example of a 1- Basic hibernate.cfg.xml configuration file:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
        <property name="connection.username">myusername</property>
        <property name="connection.password">mypassword</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>

        <!-- Mapping files -->
        <mapping resource="com/mypackage/mypersistentobject.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

Detailed explanation –

XML Part / FeatureMeaningReal-World ExampleImpact on XML File
XML Version1.0 (Standard) / 1.1 (Rare)Version of a software update1.0 is universal; 1.1 supports rare characters.
EncodingUTF-8, UTF-16, ISO-8859-1, ASCIIChoosing a keyboard languageUTF-8 supports all languages; ASCII only basic English.
DOCTYPE & DTDDefines XML rulesExam guidelines ensuring correct answersEnsures correct structure; missing DTD means no validation.
DTD URLhttp://www.hibernate.org/dtd/hibernate-configuration-3.0.dtdA reference manual for exam rulesHibernate checks this URL to verify XML correctness.
hibernate.connection.driver_classWhich database driver to useChoosing a taxi service (Ola, Uber)Determines which database (MySQL, PostgreSQL, etc.) is used.
hibernate.connection.urlWhere the database isGoogle Maps location linkSpecifies the database address and name.
hibernate.connection.usernameDatabase usernameYour login usernameIdentifies the user in the database.
hibernate.connection.passwordDatabase passwordYour login passwordGrants access to the database.
hibernate.dialectSQL syntax for HibernateChoosing a language for communicationEnsures compatibility with different databases.
hibernate.show_sqlShow SQL in logsDebug mode in a gameHelps developers see the actual queries being executed.
hbm2ddl.autoHow to handle tablesErasing or updating a whiteboardControls table creation, updates, and deletion.
<mapping resource>Maps Java class to database tableA blueprint for object-to-table conversionDefines which Java class is linked to which DB table.

Note – There are several alternative ways to create a Hibernate configuration file, instead of using a hibernate.cfg.xml file:

2- Using a Java class: A Java class can be used to create a Hibernate configuration object, which can be used to configure Hibernate.

import org.hibernate.cfg.Configuration;

public class HibernateConfig {

    public static Configuration getConfig() {
        Configuration config = new Configuration();

        config.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
        config.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/mydatabase");
        config.setProperty("hibernate.connection.username", "myusername");
        config.setProperty("hibernate.connection.password", "mypassword");
        config.setProperty("hibernate.connection.pool_size", "1");
        config.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
        config.setProperty("hibernate.current_session_context_class", "thread");
        config.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.NoCacheProvider");
        config.setProperty("hibernate.show_sql", "true");
        config.setProperty("hibernate.hbm2ddl.auto", "create");
        config.addResource("com/mypackage/mypersistentobject.hbm.xml");

        return config;
    }
}

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *