Skip to main content

Updated for Fall 2026

Hibernate

Hibernate is a great open-source framework that we will use to simplify the way we implement database persistence for Java applications. There are many reasons why Hibernate is a great choice for database persistence. This OBP section will demonstrate the power of Hibernate as well as introduce you to basic API usage.

Installing Hibernate

Hibernate should auto-install upon running the CoffeeMaker application with the correct Hibernate dependencies in the pom.xml file.

You can also read through the installation instructions on the Hibernate download page if you so desire.

Why Hibernate?

Introduction to ORM (Object-Relational Mapping)

Large applications run with a relational database to store information. The application will pull data in from the database and store that information in some model, e.g. a Java POJO (Plain Old Java Object). However, there is a disconnect between the application models and their respective database storage. Let’s consider the starting Recipe class from CoffeeMaker.

@Entity
@Table(name = "recipes")
public class Recipe {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long    id;
   private String name;
   private Integer price;
   private Integer coffee;
   private Integer milk;
   private Integer chocolate;

   // . . . Getters and setters
}

The corresponding database table would be created using the following structured query language (SQL) statement:

create table recipes (
   id BIGINT NOT NULL auto_increment,
   name VARCHAR(20) default NULL,
   price INT default NULL,
   coffee INT default NULL,
   milk INT default NULL,
   chocolate INT default NULL,
   PRIMARY KEY (id)
);

Because of the mapping between the field of the Recipe class and the attributes of the recipes table, pulling entries from the recipes table into the Recipe POJO would be rather straight forward, even without a library like Hibernate. However, what if we want to add a sugar ingredient to a Recipe? We would have to manually restructure the SQL table. While this is fine for simple applications the modification can lead to significant problems on larger, inter-dependent applications.

There are also mismatch problems that arise with relational databases like the one above:

Mismatch Description
Granularity Sometimes you will have an object model which has more classes than the number of corresponding tables in the database.
Inheritance RDBMSs (Relational Database Management Systems) do not define anything similar to Inheritance which is a natural paradigm in object-oriented programming languages.
Identity A RDBMS defines exactly one notion of ‘sameness’: the primary key. Java, however, defines both object identity (a==b) and object equality (a.equals(b)).
Associations Object-oriented languages represent associations using object references where as am RDBMS represents an association as a foreign key column.
Navigation The ways you access objects in Java and in a RDBMS are fundamentally different.

Mismatch table from this site

All of these issues with relational databases are addressed by ORM. Basically ORM provides a way to easily move data between the POJOs and relational databases (hence its name Object-Relational Mapping). A framework that provides this ORM service is called a persistence framework. Hibernate is one of those frameworks and what we will be using for implementing database persistence in CoffeeMaker.

Hibernate

Hibernate was created by Gavin King in 2001. It is an intuitive persistent framework that makes development with relational databases much easier. There are many common tasks in relational database programming that Hibernate abstracts from the developer. As a result, the technology is highly extensible and saves the developer a lot of time. By abstracting away the details of SQL, Hibernate allows the developers to focus on adding business value to their application.

Hibernate abstracts query tasks from developers by being the entity that sits between POJO instances and the relational database. When data needs to be pulled from the database, a call is made to Hibernate which in turn retrieves the data from the database and automatically inserts that data into a POJO and returns it to the caller. When data needs to be inserted into the database, a call is made to Hibernate which in turn extracts the data from the objects and inserts it into the appropriate tables. Additional advantages of Hibernate are listed in Tutorials Point’s Hibernate Overview.

In CoffeeMaker, we will be using Hibernate to translate between Java POJOs and a MySQL relational database.

Hibernate Overview

This section provides a short overview about Hibernate with examples from CoffeeMaker. For extended details see Hibernate website’s Getting Started page. If you would like to read the documentation for more information, please do so! Hibernate has a lot of great uses that can be helpful in saving you time and effort while doing your projects for this class!

Our Hibernate Configuration

Hibernate provides several options for how to configure your environment. This allows us to make informed decisions for the best option for our specific application and how we want to support it. The underlying framework works the same no matter our choice in configuration. The only difference is the syntax we will be using to set up that configuration.

We are using annotation to specify configuration details for Hibernate. Other options are to use XML or the Java Persistence API (JPA). We chose to use annotations because it lowers the number of needed files for our application as well as makes readability of the code easier since the database mappings are stored inside the POJO rather than in an external XML file.

You can look through the classes in the CoffeeMaker to follow along with how we applied configuration to the application.

Let’s walk through our Hibernate configuration. Since Spring Boot manages Hibernate for us, there are only a very few settings that we must configure ourselves

The Hibernate configuration options go in Spring’s application.properties file. When running the backend as a service, we use the application.properties in src/main/resources/ folder. For testing, we use the application.properties in src/test/resources/. There are application.properties.template in both locations as a starting version of the application.properties file. You can update the file to include the password for your local data.

NOTE: Since the application.properties file includes your database credentials, it should never be committed to Git!

Instead, we’re showing the application.properties.template, which includes no credentials and is stored in Git.

spring.application.name=coffee_maker
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/coffee_maker?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false

This table lists out all of the properties in the above file and explains what their significance is for this project.

Property Explanation
spring.application.name Name of the application
spring.jpa.hibernate.ddl-auto Specifies to update the database schema (the table representation in MySQL) against the structure of the Java classes
spring.datasource.url his specifies what the URL of the MySQL database will be. Since we put ?createDatabaseIfNotExist=true as part of the URL, Hibernate will actually instructor MySQL to create the database automatically if it does not exist yet. serverTimezone=EST solves issues relating to daylight savings time, and allowPublicKeyRetrieval=true handles changes to MySQL’s authentication system.
spring.datasource.username The username to connect to the database with
spring.datasource.password The password to connect to the database with
spring.datasource.driver-class-name This specified that we’ll be using a MySQL database, as opposed to the in-memory H2 database that Spring otherwise defaults to
spring.jpa.database-platform This specifies that we will be using the MySQL dialect when writing statements for Hibernate to execute when pushing/pulling data to/from the database. Most SQL databases use a slightly different dialect (specification) of the SQL language that are mostly, but not entirely, interchangeable. This ensures the right one is used
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults controls checks to the JDBC metadata for default setting values

Password Security

In the base CoffeeMaker, we provide application.properties.template. This file leaves the MySQL password blank. Additionally, CoffeeMaker’s .gitignore file ignores the application.properties file. This is for security. Passwords, SSH keys, and other credentials should NEVER be pushed to remote repositories, especially open repositories. Removing the password isn’t sufficient, it’s already there!. The best way to handle passwords is to store them in a configuration file locally that is never committed!

When building your project on Github Actions, we will create our own copy of application.properties and copy that into your project so that we can connect to our password protected database. Even better, the password is a secret associated with the GitHub organization so it doesn’t show up in the GitHub actions output.

Our Annotation Mappings

Okay, now we understand how we have configured Hibernate for the CoffeeMaker application . So, how does it know how to translate between the specified POJO’s? Also, since we set spring.jpa.hibernate.ddl-auto to update, Hibernate automatically updates or creates tables in the database for us. But how does it know what to put in these tables?

This is all done through the use of annotations in our POJO’s.

Let’s take a look at the Recipe.java file. Note that the Recipe class below is missing some annotations. This is because the only annotations kept below are those that are used by Hibernate to understand the way it should map between the POJO and its correlating database table.

@Entity
@Table(name = "recipes")
public class Recipe {

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;
   private String name;
   private Integer price;
   private Integer coffee;
   private Integer milk;
   private Integer sugar;
   private Integer chocolate;

   public Recipe() {
      //Needed for Hibernate to create an empty object
   }
   
   // getters and setters

}

The entire class is annotated with @Entity; this tells Hibernate that it is a Java object that it will have to map between the instance and the database entry. The @Table annotation lets us name the table something other than the class name. In this case, it would be appropriate to name the table recipes rather than recipe.

We also have an empty constructor for the Recipe class. This is required for Hibernate to work with the class. If there is not an empty constructor, Hibernate will throw an error. To avoid static analysis notifications, comment the constructor with a note about why it is there. It also helps avoid people who don’t know a lot about Hibernate coming in and deleting the constructor and breaking the application!

So now Hibernate knows about the mapping and the table. Now it needs to know about what columns to put into the table. Hibernate identifies the table attributes from the fields of the entity. Hibernate by default uses the names of the object fields as the names of the columns. Therefore, the columns of the recipes table will be id, name, price, coffee, milk, sugar, and chocolate. (If you want to specify the names of the columns, you may do so through the @Column annotation on the field.) The types of these columns will be determined by Hibernate from the types on the fields. This removes a lot of headache from the programmer since they no longer have to worry about ensuring the POJO field types and table column types map to each other correctly, Hibernate automatically handles type conversion for basic Java types!

There are several annotations that can be added to fields in specific use cases. Let’s take a look at how id is handled. Since id is a special column in the Recipe table that allows each recipe to have a unique number tied to it, we will need to specify that to Hibernate. The @Id and @GeneratedValue annotations together let Hibernate know that the id field serves this purpose. You can read up more on ids here since there are several different ways an id can be stored in a database.

Consider if we added a field that stores that date and time that Recipe was last edited:

private Date date;

The issue here is that date is a reserved word in SQL, so we wouldn’t be able to use it for a column name. Also, the Date type in java can map to several different SQL types, Hibernate wouldn’t know which one we want to use for our corresponding recipes table.

Therefore, we would need to use the following annotations to more explicitly tell Hibernate how to store the date field of Recipe. These annotations would be added to the date field, as was done with the id.

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "last_edited")
private Date date;

Annotations may be applied to the fields or to the getter/accessor methods. There is lots of discussion about where annotations go. You must have all of your annotations on either fields or methods. Trying to put some on fields and some on methods will result in some of youra nnotations being ignored by Hibernate. We encourage putting them directly on the field, as it makes it less likely that the annotations will be missed.

Using Hibernate

Now that we understand how Hibernate gets configured and how it maps between POJO’s and their respective database tables, let’s see how we actually use the framework to insert/retrieve data to/from the database.

There are three different components that are important to know about to understand using the Hibernate framework: the Persistence classes themselves, *Repository interfaces, and *Service classes. The persistence classes define the data that you want to be stored. The *Repository interfaces tell Spring how to interact with the database, and the *Service classes provide the buisiness logic for working with the entities.

Hibernate Example - Save Data

Say we want to create a new recipe and put that into the recipes table. To do so, in addition to the Recipe class we defined above, we also define a RecipeRepository and a RecipeService.

The RecipeRepository interface will look like the following:

public interface RecipeRepository extends JpaRepository<Recipe, Long> {

    Optional<Recipe> findByName ( String name );

}

This tells Spring (and in turn, Hibernate, which handles the actual Java <-> DB interaction) that we have a Recipe class that is being stored in the database, identified by (the @Id from above) a Long. Additionally, it says that we want to retrieve recipes by their name field. Optional is a generic object for handling possible exceptions that might be thrown when interacting with the database.

While this is a relatively simple example, many more details on how you can retrieve objects with Spring/Hibernate can be seen in the docs.

The RecipeService provides functionality for working with Recipes through a RecipeRepository. RecipeRepository (recall that interfaces cannot be instantiated in Java directly – Spring will create a class that implements the interface, which is then instantiated) which it uses for standard CRUD (Create, Retrieve, Update, Delete) operations on the Recipe class. The standard CRUD operations themselves are in the Service class so that they are available for all models defined in the system.

@Service
public class RecipeServiceImpl implements RecipeService {

    /** Connection to the repository to work with the DAO + database */
	@Autowired
	private RecipeRepository recipeRepository;

	/**
	 * Creates a recipe with the given information.
	 * @param recipeDto recipe to create
	 * @return created recipe
	 */
	@Override
	public RecipeDto createRecipe(RecipeDto recipeDto) {
		Recipe recipe = RecipeMapper.mapToRecipe(recipeDto);
		Recipe savedRecipe = recipeRepository.save(recipe);
		return RecipeMapper.mapToRecipeDto(savedRecipe);
	}

There’s a couple pieces of magic in this class, and we’ll defer most of the details to later on, but for now, a quick summary:

  • @Service specifies that this class is eligible for use by Spring’s dependency injection as part of other classes.
  • @Autowired uses Spring’s dependency injection to create an instance of the RecipeRepository, discussed above

RecipeService can save a Recipe to the database through RecipeRepository.save().

Hibernate Example - Retrieve Data

Retrieving Recipes from the database is every bit as easy as creating them:

RecipeService can call RecipeRepository.findById() or RecipeRepository.findByName().

The best news is that through a combination of Spring’s dependency injection, Hibernate’s Java <-> Database functionality the *Service classes can provide the logic for working with the entities! You can create other persistence classes (as you’ll be doing later in the project) and getting Spring and Hibernate to make them work with the database is as simple as what we’ve just seen.

Testing Persistent POJOs

There are some nuances to testing persistent POJOs (POJOs that directly map to a database). When writing unit tests, we like to start with a new object or a common starting point. With databases, that may not always be the case. One way to handle testing databases is to always clear the database before testing. However, that requires a test database separate from the production database, which is good practice. We have an application.properties file that handles a separate database for testing.

There are several resources for unit testing persistent POJOs:

References