Hibernate Example using JPA and MySQL
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is a java framework that is used to develop persistence logic. More precisely Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework to develop objects which are independent of the database software and make independent persistence logic in all JAVA, JEE.
JPA stands for Java Persistence API. It is known as Java specification which provides some functionality and standard to ORM tools. It is used to control, review and persist data between Java objects and databases. It is regarded as the standard technique for Object Relational Mapping. Sometimes Geeks got confused between JPA and Hibernate. So here are some basic differences between JPA and Hibernate.
|JPA is not an implementation. It is only a Java specification.||Hibernate is an implementation of JPA.|
|JPA explains the handling of data in Java applications.||Hibernate is an ORM (Object-Relational Mapping) tool that is used to save the Java objects in the database system.|
|As an object-oriented query language, JPA uses JPQL (Java Persistence Query Language) to execute database operations.||As an object-oriented query language, it uses Hibernate Query Language (HQL) to execute database operations.|
Implementation: We are going to build a simple Java application by creating a maven project and we are going to save some data inside the MySQL Database with the help of both Hibernate and JPA concepts.
Step 1: Create a maven project in your favorite Java IDE (In this article we are using IntelliJ IDEA)
Step 2: When you have successfully created a maven project you have to add some dependencies in your pom.xml file. You have to add the following dependency in your pom.xml file.
Dependency for Hibernate is as follows:
Dependency for MySQL is as follows:
Example: pom.xml File
Step 3: Create a simple POJO class and name the class as Song.
Step 4: 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.
Example: hibernate.cfg.xml File
Step 5: Create a class named App and inside the class write the main() method
Step 6: Create a schema named hibernate-demo (you can choose your own) inside your MySQL Database. And run your application.
You 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.