The article JPA - Hello, World! using Hibernate explains how to use Hibernate v4.x. This tutorial introduces using JPA with the latest Hibernate v5.2.3. Same as the previous article, it also targets beginners who are new to Hibernate and JPA.
You need Java 1.8, Eclipse for Java EE developers and MySQL server in your system in-order to try this tutorial.
Step 1:
Step 1:
Create a database “javahelps” and a table “student” in MySQL.
CREATE DATABASE IF NOT EXISTS javahelps;
CREATE TABLE javahelps.student (
student_id INT NOT NULL ,
student_name VARCHAR(45) NOT NULL ,
student_age INT NOT NULL ,
PRIMARY KEY (student_id) );
Step 2:
Create a new Maven project “JPAWithHibernate5” in Eclipse using the following configuration.
Group id: com.javahelpsArtifact id: JPAWithHibernate5
Step 3:
Open the pom.xml and add the following dependencies and plugin.
<!-- Logback to print the logs generated by Hibernate -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
<!-- Core of Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.3.Final</version>
</dependency>
<!-- Entity manager which is required for JPA -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.3.Final</version>
</dependency>
<!-- JDBC Connector for MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.4</version>
</dependency>
<!-- This plugin is used to set the Java version 1.8 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
After the modification, pom.xml should look like this:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javahelps</groupId>
<artifactId>JPAWithHibernate5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- Logback to print the logs generated by Hibernate -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
<!-- Core of Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.3.Final</version>
</dependency>
<!-- Entity manager which is required for JPA -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.3.Final</version>
</dependency>
<!-- JDBC Connector for MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- This plugin is used to set the Java version 1.8 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Right click on the project and select Maven → Update Project → Click OK on the appeared dialog to apply the changes done in the pom file.Step 4:
Create a new package “com.javahelps.jpa” in src/main/java folder.
Create a new class Student inside the package as shown below.
package com.javahelps.jpa;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "student")
public class Student implements Serializable {
@Id
@Column(name = "student_id", unique = true)
private int id;
@Column(name = "student_name", nullable = false)
private String name;
@Column(name = "student_age", nullable = false)
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return id + "\t" + name + "\t" + age;
}
}
Step 6:
Right click on the src/main/resources folder and create a new folder META-INF.
Create a new file persistence.xml, in the META-INF folder and modify the content as shown below.
<persistence xmlns="http://java.sun.com/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_0.xsd"
version="2.0">
<persistence-unit name="JavaHelps" transaction-type="RESOURCE_LOCAL">
<!-- Persistence provider -->
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<!-- Entity classes -->
<class>com.javahelps.jpa.Student</class>
<properties>
<!-- The JDBC URL to the database instance -->
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/javahelps?useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC" />
<!-- The database username -->
<property name="javax.persistence.jdbc.user" value="root" />
<!-- The database password -->
<property name="javax.persistence.jdbc.password" value="root" />
</properties>
</persistence-unit>
</persistence>
In this configuration file, change the username and password of the database according to your database. With the new Hibernate and JDBC, you do not need to specify the JDBC driver in the persistence.xml file but due to a bug in JDBC Connector, the timezone configurations are required in the JDBC url.
Note: When you add the above code, replace all the & signs in the JDBC URL by &
Note: When you add the above code, replace all the & signs in the JDBC URL by &
Step 8:
Create a new Java class Main.java with main method.
Step 9:
Create an EntityManagerFactory and initialize it as shown below. The persistence unit name used to create the EntityManagerFactory, should match with the name defined in the persistence.xml file.
package com.javahelps.jpa;
import java.util.List;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
// Create an EntityManagerFactory when you start the application.
private static final EntityManagerFactory ENTITY_MANAGER_FACTORY = Persistence
.createEntityManagerFactory("JavaHelps");
}
Step 10:
Add the CRUD methods to the Main class and access them from the main method as given below:
package com.javahelps.jpa;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
public class Main {
// Create an EntityManagerFactory when you start the application.
private static final EntityManagerFactory ENTITY_MANAGER_FACTORY = Persistence
.createEntityManagerFactory("JavaHelps");
public static void main(String[] args) {
// Create two Students
create(1, "Alice", 22); // Alice will get an id 1
create(2, "Bob", 20); // Bob will get an id 2
create(3, "Charlie", 25); // Charlie will get an id 3
// Update the age of Bob using the id
upate(2, "Bob", 25);
// Delete the Alice from database
delete(1);
// Print all the Students
List<Student> students = readAll();
if (students != null) {
for (Student stu : students) {
System.out.println(stu);
}
}
// NEVER FORGET TO CLOSE THE ENTITY_MANAGER_FACTORY
ENTITY_MANAGER_FACTORY.close();
}
/**
* Create a new Student.
*
* @param name
* @param age
*/
public static void create(int id, String name, int age) {
// Create an EntityManager
EntityManager manager = ENTITY_MANAGER_FACTORY.createEntityManager();
EntityTransaction transaction = null;
try {
// Get a transaction
transaction = manager.getTransaction();
// Begin the transaction
transaction.begin();
// Create a new Student object
Student stu = new Student();
stu.setId(id);
stu.setName(name);
stu.setAge(age);
// Save the student object
manager.persist(stu);
// Commit the transaction
transaction.commit();
} catch (Exception ex) {
// If there are any exceptions, roll back the changes
if (transaction != null) {
transaction.rollback();
}
// Print the Exception
ex.printStackTrace();
} finally {
// Close the EntityManager
manager.close();
}
}
/**
* Read all the Students.
*
* @return a List of Students
*/
public static List<Student> readAll() {
List<Student> students = null;
// Create an EntityManager
EntityManager manager = ENTITY_MANAGER_FACTORY.createEntityManager();
EntityTransaction transaction = null;
try {
// Get a transaction
transaction = manager.getTransaction();
// Begin the transaction
transaction.begin();
// Get a List of Students
students = manager.createQuery("SELECT s FROM Student s", Student.class).getResultList();
// Commit the transaction
transaction.commit();
} catch (Exception ex) {
// If there are any exceptions, roll back the changes
if (transaction != null) {
transaction.rollback();
}
// Print the Exception
ex.printStackTrace();
} finally {
// Close the EntityManager
manager.close();
}
return students;
}
/**
* Delete the existing Student.
*
* @param id
*/
public static void delete(int id) {
// Create an EntityManager
EntityManager manager = ENTITY_MANAGER_FACTORY.createEntityManager();
EntityTransaction transaction = null;
try {
// Get a transaction
transaction = manager.getTransaction();
// Begin the transaction
transaction.begin();
// Get the Student object
Student stu = manager.find(Student.class, id);
// Delete the student
manager.remove(stu);
// Commit the transaction
transaction.commit();
} catch (Exception ex) {
// If there are any exceptions, roll back the changes
if (transaction != null) {
transaction.rollback();
}
// Print the Exception
ex.printStackTrace();
} finally {
// Close the EntityManager
manager.close();
}
}
/**
* Update the existing Student.
*
* @param id
* @param name
* @param age
*/
public static void upate(int id, String name, int age) {
// Create an EntityManager
EntityManager manager = ENTITY_MANAGER_FACTORY.createEntityManager();
EntityTransaction transaction = null;
try {
// Get a transaction
transaction = manager.getTransaction();
// Begin the transaction
transaction.begin();
// Get the Student object
Student stu = manager.find(Student.class, id);
// Change the values
stu.setName(name);
stu.setAge(age);
// Update the student
manager.persist(stu);
// Commit the transaction
transaction.commit();
} catch (Exception ex) {
// If there are any exceptions, roll back the changes
if (transaction != null) {
transaction.rollback();
}
// Print the Exception
ex.printStackTrace();
} finally {
// Close the EntityManager
manager.close();
}
}
}
Run the project and check the output.
Step 12:
To avoid unnecessary console output caused by Hibernate debug logs, create a new file logback.xml in src/main/resources folder with the following content.
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator" />
<!-- Format the log output -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
</pattern>
</encoder>
</appender>
<!-- Set the application log level to INFO -->
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
<!-- Set log level of Hibernate to WARN level -->
<logger name="org.hibernate">
<level value="WARN" />
</logger>
</configuration>
Find the Maven project at Git Hub.
11 comments
Write commentsHi Gobinath, i found this error. how to solve it? TQ in advance.
Reply[main] INFO org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl - HHH000115: Hibernate connection pool size: 20 (min=1)
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Hi,
ReplyCan you share the complete error log so that I can figure out the exact reason for this exception. Also make sure that you are using the exact Hibernate and MySQL versions given in Step 3.
This is my pom.xml .
Reply4.0.0
com.javahelps
JPAWithHibernate5
0.0.1-SNAPSHOT
ch.qos.logback
logback-classic
1.1.7
org.hibernate
hibernate-core
5.2.3.Final
org.hibernate
hibernate-entitymanager
5.2.3.Final
mysql
mysql-connector-java
6.0.4
org.apache.maven.plugins
maven-compiler-plugin
3.5.1
1.8.0_101
1.8.0_101
It seems to be fine. Can you share the complete error log (The stack trace). If you do not get the full error log, change the log level to DEBUG as shown below in logback.xml.
Reply<!-- Set log level of Hibernate to WARN level -->
<logger name="org.hibernate">
<level value="WARN" />
</logger>
Hi rozie,
ReplyPlease accept my apologies for the late response as I didn't notice your comment because it was marked as spam by Disqus. The problem is due to a bug in the MySQL connector. To overcome this problem, use the following jdbc url in persistence.xml.
<properties>
<!-- The JDBC URL to the database instance -->
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/javahelps?useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC" />
<!-- Other properties here -->
</properties>
Hi,
ReplyThe problem is due to a bug in the MySQL connector. To overcome this problem, use the following jdbc url in persistence.xml.
<properties>
<!-- The JDBC URL to the database instance -->
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/javahelps?useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC" />
<!-- Other properties here -->
</properties>
no problem at all. Thanks a lot!! i can use it now.... :)
ReplyGreat!!!!!
ReplyThank's
Hi Mr. Gobinath,
Replythanks for your post.
I think that with Hibernate-core v.5.x it is not neccesary Hibernate -entity-manger. Maybe I am mistaken. What do you think?. Thanks
You're not wrong. If it was pure Hibernate not JPA, we'd be accessing the code with the HibernateSession, not the EntityManager. But regardless, it's the HibernateSession under the covers doing all the JDBC work.
ReplyHi!
ReplyInside Main#update after manager.find(...) we get a managed entity from persistence context, so why do we use manager.persist(...)? Any changes to the entity will be saved after trasnsaction commit. Am I right? No?)
EmoticonEmoticon