A simple console application demonstrating how to use Hibernate and JPA to save Java objects to a MySQL database. This project is a beginner-friendly example of basic Object-Relational Mapping (ORM).
Java 17
Hibernate ORM 6.2
JPA (Jakarta Persistence)
MySQL 8.0
Maven
JPA Annotations: Uses @Entity, @Table, @Id, and @Column to map a Song POJO to a database table.
Automatic ID Generation: Uses @GeneratedValue to let MySQL handle primary key creation (auto-increment).
Configuration: Connects to the database using the hibernate.cfg.xml configuration file.
CRUD Operation: Demonstrates the Create operation by persisting Song objects to the database.
Transaction Management: Correctly wraps database operations in a single Session transaction.
Before you begin, ensure you have the following installed:
Java JDK 17 or newer.
Apache Maven.
MySQL Server (running on localhost:3306).
git clone https://github.com/your-username/your-repository-name.git cd your-repository-name
Open MySQL Workbench or your preferred SQL client and run the following command to create the database schema:
CREATE DATABASE hibernatedemo;
Open the src/main/resources/hibernate.cfg.xml file.
Find these lines and update the password to match your local MySQL root password. You may also need to change the username if it's not root.
root your_password
This project is set to hibernate.hbm2ddl.auto=create, so the first time you run it, Hibernate will automatically create the song table for you.
Let Maven build the project (your IDE usually does this automatically).
Run the main() method in the src/main/java/org/example/App.java file.
After running, you can check your MySQL hibernate_demo database. You will see a song table with the new records in it!
SELECT * FROM hibernatedemo.song;
Aman Manwatkar