Hibernate JPA Example

0

In this article, we will look into the JPA APIs for object persistence and we will use Hibernate as the JPA engine.

Hibernate as JPA engine

Hibernate can be JPA-compliant through the Hibernate EntityManager extension module.
If you are using maven as build tool, then you need to add the following dependency:
pom.xml:

 		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<${hibernate.version}>
		</dependency>

If you don’t add and try to use JPA APIs, you will get the below error:
javax.persistence.PersistenceException: No Persistence provider for EntityManager named employee

In our example, we will use extension module of ver 4.0.1.Final.

The configuration of JPA is based on XML file persistence.xml, located in the META-INF directory of the classpath root.

persistence.xml:

<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_1_0.xsd"
	version="1.0">
	<persistence-unit name="employee">
		<properties>
			<property name="hibernate.ejb.cfgfile" value="/hibernate.cfg.xml" />
		</properties>
	</persistence-unit>
</persistence>

In this file, you can set any vendor-specific properties for the underlying engine configuration.
A persistence unit defines a set of persistent classes and how they should be persisted. Each persistence unit requires a name for identification.
Since we are configuring Hibernate as the underlying JPA engine, we need to add hibernate.ejb.cfgfile property and set its value to the Hibernate configuration file located in the classpath root.

If you notice, we haven’t added any class attribute. This is because Hibernate EntityManager will automatically detect XML mapping files and JPA annotations as mapping metadata so we don’t have to specify them explicitly.

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">mnrpass</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hbm2ddl.auto">update</property>
    </session-factory>
</hibernate-configuration>

In this example, we won’t rely on mapping file and use annotations. Let’s look at our Employee class. Since it is an entity class that we should be able to persist it, in order to mark the bean as an entity class, we need to annotate with the runtime annotation @Entity. You can assign a table name for an entity class using @Table. For each property, you can specify a column name and details using @Column. Each entity class must have an identifier defined by the @Id annotation. You can also choose a strategy for identifier generation using the @GeneratedValue .

Employee:

package com.javarticles.hibernate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="emp")
public class Employee {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private long id;
    
    @Column(name="name", length=100, nullable=false)
    private String name;
    
    @Column(name="contract", length=100)
    private String contact;
    
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getContact() {
        return contact;
    }
    public void setContact(String contact) {
        this.contact = contact;
    }
    public String toString() {
        return "Employee: " + name;
    }   
}

If you have used hibernate APIs before, you can easily relate it to JPA APIs.
EntityManagerFactory is similar to SessionFactory. As you obtain Session object from SessionFactory, you can obtain EntityManager from EntityManagerFactory.
Below is the example where we create an Employee object. Before we start creating employee, we make sure it doesn’t already exists. If it does, we will delete it and then go for creation. In the end, we will retrieve what we have created.

HibernateJpaExample:

package com.javarticles.hibernate;

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;

import org.hibernate.MappingException;

public class HibernateJpaExample {

    public static void main(String[] args) throws MappingException, IOException {
        EntityManager manager = Persistence.createEntityManagerFactory(
                "employee").createEntityManager();
        System.out.println("Delete if already added");
        Query query = manager.createQuery("from Employee where name = 'Jim'");
        List empList = query.getResultList();
        if (!empList.isEmpty()) {
            EntityTransaction tx = manager.getTransaction();
            tx.begin();
            for (Employee emp : empList) {
                System.out.println("Delete emp " + emp);
                manager.remove(emp);
            }
            tx.commit();
        }

        System.out.println("Create new employee");
        EntityTransaction tx = manager.getTransaction();
        tx.begin();
        Employee emp = new Employee();
        emp.setName("Jim");
        manager.merge(emp);
        tx.commit();
        
        empList = query.getResultList();
        System.out.println("Employees: " + empList);        
    }
}

Output:

Delete if already added
Create new employee
Employees: [Employee: Jim]

Download Source Code

In this article, I have shown you an example of Hibernate compliant JPA style persistence. You can download the source code here: hibernateJpa.zip

Share.

Leave A Reply