VOOZH about

URL: https://www.geeksforgeeks.org/java/hibernate-example-using-jpa-and-mysql/

⇱ Hibernate Example using JPA and MySQL - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Hibernate Example using JPA and MySQL

Last Updated : 9 Apr, 2026

Hibernate with JPA simplifies database interaction in Java by allowing developers to work with objects instead of writing complex SQL. It reduces boilerplate code and provides a standardized way to manage data persistence. Using MySQL with Hibernate ensures efficient and structured data storage.

  • Maps Java classes directly to database tables
  • Easily connects with MySQL using configuration
  • Handles data operations reliably with JPA standards

Step-by-Step Implementation to use Jpa with Mysql database

Step 1: Create a Maven Project

Open your IDE (IntelliJ IDEA, Eclipse or STS). Create a New Maven Project.

  • GroupId: org.example
  • ArtifactId: hibernateapp
  • Version: 1.0-SNAPSHOT
👁 New Project Creation

Step 2: Add Dependencies in pom.xml

We need Hibernate ORM and MySQL connector dependencies.

<dependency>

<groupId>org.hibernate.orm</groupId>

<artifactId>hibernate-core</artifactId>

<version>6.2.7.Final</version>

</dependency>

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>8.0.33</version>

</dependency>

Example: pom.xml File

Step 3: Create Entity Class (Song.java)

Create a simple POJO class and name the class as Song. 

Step 4: Configure Hibernate (hibernate.cfg.xml)

Create a hibernate configuration file (XML file) inside the src > main > resources folder. Here we have named the file hibernate.cfg.xml. In this file, we are going to configure all the properties for the MySQL Database.

hibernate.cfg.xml File 

Step 5: Create Main Class (App.java)

Create a class named App and inside the class write the main() method

Example:

Step 6: Create Database Schema in MySQL

Create a schema named hibernate-demo (you can choose your own) inside your MySQL Database. And run your application.

Run the following command in MySQL Workbench or CLI:

CREATE DATABASE hibernate-demo;

Output:

After running the project, check MySQL Workbench

SELECT * FROM song;

👁 Output in MySQL Workbench

We can see the data has been saved inside your MySQL workbench. And in the hibernate-demo schema, a table named song has been created and the corresponding values for each column that you have set in App.java class have been stored.  

Comment
Article Tags: