Hibernate 5 JPA Configuration in application
The JPA API depends on one of the persistence provider for performing ORM and persistence activities. Hibernate is one of many persistence provider for JPA applications. In this lesson you will learn to use Hibernate 5 JPA Configuration file to make fully functional application.
The persistence.xml is configuration file used in Java persistence where developers can configure database details, connection pool and Entity used the application.
In the persistence.xml developer configures:
- Entity class
- Dialect class
- Persistence provider class
- Database url
- Database user name
- Database password and database name
- It is also used to provide other values like show_url, format_sql etc..
This file is importance and used by EntityManagerFactory while initializing the EntityManagerFactory.
We have tutorial of using Hibernate 5 with JPA at Hibernate 5 JPA Tutorial, here you will find full source code of integrated Hibernate JPA application.
Now lets see the full code of persistence.xml JPA configuration file.
Here is simple example of persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_1.xsd"> <persistence-unit name="psunit1"> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <class>net.roseindia.model.Car</class> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/> <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/jpa?useUnicode=true&characterEncoding=UTF-8"/> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/> <property name="hibernate.connection.username" value="root"/> <property name="hibernate.connection.password" value="root"/> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.format_sql" value="true"/> </properties> </persistence-unit> </persistence>
Above persistence.xml file connects to MySQL database and initializes the persistence unit name "punit1". You can define a number of persistence unit in the persistence.xml file if you are connection to multiple databases.
We have used HibernatePersistenceProvider from Hibernate framework.
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
In this tutorial I explained you the Hibernate 5 JPA Configuration code which you can used to use Hibernate 5 and JPA together in your Java program.
View complete detail and download source code of this example at Hibernate 5 JPA Tutorial page.
Here are more Hibernate 5 tutorials: