Hibernate 5 persistence.xml example

Learn to use Hibernate 5 persistence.xml file with example code in Eclipse.

Hibernate 5 persistence.xml example

Hibernate 5 persistence.xml example - Write integrated code example

The persistence.xml is configuration file used in JPA application. In this example we will learn to use Hibernate 5 persistence.xml file for making a simple example program.

The EntityManager API provides functions to perform database related operations. In Java program its instance is obtained from EntityManagerFactory and the instance of EntityManagerFactory is created with the help of bootstrap class javax.persistence.Persistence. The bootstrap process uses persistence.xml file where we provide database access details and configuration of various Entity classes.

The persistence.xml file is used to configure Entity classes, provide database driver, dialect class, database connection information and other relational mapping details.

The persistence.xml file provides full control on the JPA environment configuration to developer. Both Java SE and Java EE container uses persistence.xml file to configure Persistence Context in the application.

In web application you can bootstrap JPA environment during startup of the application. It can also be configured to use JDBC connection pool for maximum performance.

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" 
  <persistence-unit name="psunit1">
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
            <property name="hibernate.connection.url" 
            <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"/>

In the above file we have configured it to connect it to MySQL database. Database connection details can be configured to use any other database.

If you are looking for full code example of using persistence.xml file in Java project then check our tutorial Hibernate 5 JPA Tutorial.

View complete detail and download source code of this example at Hibernate 5 JPA Tutorial page.

Here are more Hibernate 5 tutorials: