![]() |
VOOZH | about |
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.
Open your IDE (IntelliJ IDEA, Eclipse or STS). Create a New Maven Project.
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
Create a simple POJO class and name the class as Song.
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
Create a class named App and inside the class write the main() method
Example:
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
👁 Output in MySQL WorkbenchSELECT * FROM song;
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.