JPA EntityManager Example
This tutorial shows how to work with the Java Persistence API. The purpose of JPA is to create an abstraction layer between the database layer and an ORM framework. This enables us to loosely couple our code with any ORM framework and easily change from vendor.
We demonstrate this with the following example. We start by configuring the persistence unit using the persistence.xml
file, located at the src/main/resources/META-INF
directory.
When the persistence unit is configured properly, we can create a EntityManager
, which is used to manage the state of the entity.
Project Structure
Make sure the persistence.xml
file is located in the META-INF
directory.
Maven Dependencies
We use Apache Maven to manage the projects dependencies.
<?xml version="1.0" encoding="UTF-8"?>
<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.memorynotfound.db.hibernate.configuration</groupId>
<artifactId>entity-manager</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>HIBERNATE - ${project.artifactId}</name>
<url>https://memorynotfound.com</url>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.4</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.3.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.3.Final</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Create Model Class + Mapping
The following Event
class will be persisted using the JPA Entity Manager.
package com.memorynotfound.hibernate;
import javax.persistence.*;
import java.io.Serializable;
@Entity
public class Event implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
public Event() {
}
public Event(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Event{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
If you prefer XML over Annotations, you can use the equivalent JPA XML mapping. This file is located in the src/main/resources/META-INF
folder and is named orm.xml
.
<?xml version="1.0" encoding="UTF-8" ?>
<entity-mappings xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm
http://xmlns.jcp.org/xml/ns/persistence/orm_2_0.xsd" version="2.0">
<entity class="com.memorynotfound.hibernate.Event">
<attributes>
<id name="id">
<generated-value strategy="IDENTITY"/>
<column name="event_id"/>
</id>
<basic name="name">
<column name="name"/>
</basic>
</attributes>
</entity>
</entity-mappings>
Configure JPA Persistence Unit
We configure the JPA Persistence Unit using the persistence.xml
file, which is located in the src/main/resources/META-INF
directory.
<?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://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="mnf-pu" transaction-type="RESOURCE_LOCAL">
<!-- enable if you prefer xml over annotations
<mapping-file>META-INF/orm.xml</mapping-file>
-->
<properties>
<!-- Configuring JDBC properties -->
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/memorynotfound?serverTimezone=Europe/Brussels"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<!-- Hibernate properties -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.show_sql" value="true"/>
<!-- Configuring Connection Pool -->
<property name="hibernate.c3p0.min_size" value="5"/>
<property name="hibernate.c3p0.max_size" value="20"/>
<property name="hibernate.c3p0.timeout" value="500"/>
<property name="hibernate.c3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.idle_test_period" value="2000"/>
</properties>
</persistence-unit>
</persistence>
Create, Run and Test Application
We can create an EntityManagerFactory
using the Persistence.createEntityManagerFactory("name-of-persistence-unit")
. Using this factory we create the EntityManager
. This EntityManager
manages our entities and can execute CRUD
operations using the EntityTransaction
.
package com.memorynotfound.hibernate;
import javax.persistence.*;
public class App {
public static void main (String...args) throws InterruptedException {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hibernate-dynamic");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Event event = new Event();
event.setName("JPA EntityManager Example - Using Hibernate");
em.persist(event);
em.getTransaction().commit();
emf.close();
}
}
The previous code generates the following output.
Hibernate: drop table if exists Event
Hibernate: create table Event (id integer not null auto_increment, name varchar(255), primary key (id))
Hibernate: insert into Event (name) values (?)
Hibernate: drop table if exists Event