Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Hibernate Config and Entities | Fundamentals of Hibernate
Java Data Manipulation with Hibernate
course content

Зміст курсу

Java Data Manipulation with Hibernate

Java Data Manipulation with Hibernate

1. JDBC Overview
2. Fundamentals of Hibernate
3. Final Touches

book
Hibernate Config and Entities

Let's start learning Hibernate with the basics of interfaces and annotations. The first thing we should do is to integrate Hibernate into your project. It all begins, as always, with importing dependencies.

Importing and Configuring Hibernate

Let's start with the familiar procedure of importing Hibernate into the project. To do this, we need to open the already familiar pom.xml file and add the Hibernate dependency import there. You can find the latest version of Hibernate at this link.

As you can see, I'm using version 6.3.1, which was the latest at the time of creating this course. Your version may vary slightly, but I believe that the core annotations and functions will remain the same as before.

One import won't be enough for us, so we need to import another dependency to connect our application to the MySQL database management system (DBMS). More specifically, we need to import the JDBC connector for MySQL, which we will use to connect to the database.

You can find the latest version at this link.

hibernate.cfg.xml

We have finished with the importing process, and now we need to configure Hibernate correctly. We will do this in the hibernate.cfg.xml file, which should be located in the src/main/resources folder.

I will provide you with a template of how the configuration should look like at this point in the course, and then I will explain what it means:

  1. XML Declaration and DOCTYPE:

    • <?xml version="1.0" encoding="utf-8"?> declares that this is an XML file version 1.0 with UTF-8 encoding;
    • <!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> specifies the document type and refers to the DTD for Hibernate configuration, aiding in XML file structure validation.
  2. Session Factory Configuration:

    • The <hibernate-configuration> element wraps the entire Hibernate configuration;
    • Inside <session-factory>, settings for the Hibernate session factory are specified, managing database sessions.
  3. JDBC Setup:

    • hibernate.connection.driver_class: JDBC driver class for database connection, here for MySQL.
    • hibernate.connection.url: Database connection URL;
    • hibernate.connection.username: Username for database access;
    • hibernate.connection.password: Password for database access.
  4. Dialect Setup:

    • hibernate.dialect: Instructs Hibernate which SQL dialect to use for generating database-specific SQL queries, here for MySQL.
  5. SQL Display and Formatting Settings:

    • show_sql: If true, Hibernate shows all SQL queries in the console;
    • format_sql: If true, formats SQL queries for readability.
  6. Session Management:

    • hibernate.current_session_context_class: Specifies how to manage the current session context, here through threads (thread), allowing use of SessionFactory.getCurrentSession() to obtain the current session in the thread.

This setup initializes and configures the Hibernate environment, defining how the application connects to the database, what SQL settings to use, and how to manage sessions for database interactions.

In our case, all you need to specify in this configuration is the link to your database (if its name is different from the one we created in the previous chapter), the MySQL username, which is usually 'root,' and the password. You can find the address of your database and the table you'll be working within MySQL Workbench, as shown in the screenshots:

Entity

Now that we have configured the database connection and Hibernate, it's time to start working with entities. Let's begin by understanding what a class-entity in Hibernate is all about:

For a class to be considered an entity class in Hibernate, it must meet a few requirements:

  • @Entity Annotation: The class must be annotated with @Entity, indicating to Hibernate that this class is an entity class. This annotation tells Hibernate to treat the class as an entity that needs to be mapped to a database table;

  • No-argument Constructor: The entity class should have a public or protected no-argument constructor. Hibernate uses this constructor to instantiate objects of the Entity class;

  • Identifier Attribute: Each entity class must have a primary key, which is mapped using @Id annotation. This attribute serves as a unique identifier for each entity instance;

  • Class Attributes: The attributes of the class represent the columns of the table. These can be mapped to database columns using annotations like @Column;

  • Access Modifiers: While it's not a strict requirement, it's a good practice to make fields private and provide public getters and setters. Hibernate can access fields directly or through these getters and setters.

An example of an Entity class from the previous chapter:

As you can see, we're replicating the values from the table in this entity class. We also use Project Lombok to save some space on your screen :).

We use annotations like @NoArgsConstructor, and @Data from the Project Lombok to make this class meet the requirements of an Entity class.

Next, let's go step by step. We named the class Employee because this class serves as a model and representation of an object from the employees table. We specify the table name in the @Table annotation parameters as follows: @Table(name = "employees"). We also mark this class with the @Entity annotation.

Note

In Java, many things are done using annotations, so you will often encounter a large number of annotations. For example, the Spring Boot framework is also almost entirely built on annotations and is constantly used in development.

In the Employee class, there is an id field, which represents a unique identifier. As stated in the requirements, we have designated it with the @Id annotation and @GeneratedValue. The second annotation is used to automatically increment the value of the id attribute when adding an element, ensuring that there are no duplicate IDs in the table. This way, we can maintain the uniqueness of each element in the table.

Note

For example, if the maximum id in the table is 5, when adding a new element, we don't need to specify a new id; it is automatically incremented and assigned the value 6.

Each of the other attributes, which directly correspond to columns in the employees table, we annotate with @Column, where we specify the column name in the table. This allows Hibernate to precisely identify the columns we need.

Summary Algorithm

Well, let's recap the algorithm:

  • An entity class represents a table, and objects of this class represent rows in that table, storing their values;
  • Such a class should have fields identical to the columns in the table. Additional fields can also be added if required by the business logic;
  • The class should be marked with the @Entity annotation, and the appropriate fields should use annotations like @Column, @Id, and @GeneratedValue;
  • It's good practice to make fields in such a class private and access them through getters and setters;
  • Additional methods can be added to such classes if the business logic requires it, but it's not recommended. Methods for working with this class should be placed in separate interfaces and implementation classes. This is guided by the DAO design pattern.

In the upcoming chapters, you will create your own entity class that meets all these standards. In practice, you always gain an understanding of how and what to use.

1. What is the first step in integrating Hibernate into your project?
2. Which file is used to configure Hibernate?
3. What is the purpose of the `@Entity` annotation in Hibernate?
4. What does the `@Id` annotation indicate in a Hibernate entity class?
5. How does Hibernate determine which SQL dialect to use for generating database-specific SQL queries?
What is the first step in integrating Hibernate into your project?

What is the first step in integrating Hibernate into your project?

Виберіть правильну відповідь

Which file is used to configure Hibernate?

Which file is used to configure Hibernate?

Виберіть правильну відповідь

What is the purpose of the `@Entity` annotation in Hibernate?

What is the purpose of the @Entity annotation in Hibernate?

Виберіть правильну відповідь

What does the `@Id` annotation indicate in a Hibernate entity class?

What does the @Id annotation indicate in a Hibernate entity class?

Виберіть правильну відповідь

How does Hibernate determine which SQL dialect to use for generating database-specific SQL queries?

How does Hibernate determine which SQL dialect to use for generating database-specific SQL queries?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 2
We're sorry to hear that something went wrong. What happened?
some-alt