Title: Hibernate 4.3 and JPA 2.1 Example

Summary: Hibernate 4.3 and JPA 2.1 Example: Create code using the latest version of Hibernate 4.3 and JPA 2.1

ID:  50227

Home ID:  50009

------------------------------------------------------------------------------

How to create Hibernate 4.3 and JPA 2.1 Example program?

In this tutorial I will teach you how to write program using the latest Hibernate 4.3 and JPA 2.1 Example. You will learn how to create the persistence.xml file with proper configuration. We are using the Maven 3 build tool as it automatically downloads the dependencies need by the program. We will also use the Maven to run the example code.

You can use the source code of this project and import it in Eclipse IDE and then use any maven plugin to run it from the Eclipse IDE.

Hibernate 4.3.x is developed to support the JPA 2.1 specification. You can use the Hibernate 4.3.x in your JPA 2.1 based projects.

I am assuming that you have knowledge of Hibernate and JPA.

So, let's start developing the program.

Step 1: Create database and table

We are using MySQL database, Here is the query to create database:

create database jpa;

Now create the table using following SQL:

CREATE TABLE `products` (                                
            `id` int(11) NOT NULL AUTO_INCREMENT,                  
            `product_name` varchar(250) DEFAULT NULL,              
            `product_description` varchar(400) DEFAULT NULL,       
            `stock_qty` double(10,2) DEFAULT NULL,                 
            `price` double(10,2) DEFAULT NULL,                     
            PRIMARY KEY (`id`)                                     
   ) ENGINE=InnoDB;

Step 2: Create the entity class

Here is the code of the Entity class:

package net.roseindia.model;

import javax.persistence.*;

/**
* @author Deepak Kumar
* More tutorials at http://www.roseindia.net
*/

@Entity
@Table(name="products")
public class Product {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int id;
	
	@Column(name="product_name")
	private String productName;
	
	@Column(name="product_description")
	private String productDescription;
	
	@Column(name="stock_qty")
	private Double stockQty;
	
	@Column(name="price")
	private Double price;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getProductName() {
		return productName;
	}

	public void setProductName(String productName) {
		this.productName = productName;
	}

	public String getProductDescription() {
		return productDescription;
	}

	public void setProductDescription(String productDescription) {
		this.productDescription = productDescription;
	}

	public Double getStockQty() {
		return stockQty;
	}

	public void setStockQty(Double stockQty) {
		this.stockQty = stockQty;
	}

	public Double getPrice() {
		return price;
	}

	public void setPrice(Double price) {
		this.price = price;
	}
	

}

You can view the details of the annotations used here at http://www.roseindia.net/jee/jee7/jpa/first-jpa-example.shtml

Step 3: Create persistence.xml file

Here is the 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.Product</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>

In the above file you will find the org.hibernate.jpa.HibernatePersistenceProvider, which is the persistence provide in of Hibernate. In the above file we have other properties like database url, username and password. You can change these values to map to your database.

Step 4: Code for executing the example

Here is the code for executing the example program:

package net.roseindia;

import net.roseindia.model.*;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.ParameterMode;
import javax.persistence.Persistence;
import javax.persistence.StoredProcedureQuery;
		/*
		//Compile mvn compile
		//Run: mvn exec:java -Dexec.mainClass="net.roseindia.AppTest"
		
		*/
/**
* @author Deepak Kumar
* More tutorials at http://www.roseindia.net
*/
		
public class AppTest {

	private static final String PERSISTENCE_UNIT_NAME = "psunit1";
	private static EntityManagerFactory factory;

	public static void main(String[] args) {
		factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
		EntityManager em = factory.createEntityManager();

		em.getTransaction().begin();
		
		Product product = new Product();
		product.setProductName("JPA 2.1 Book");
		product.setProductDescription("This is the latest book on JPA 2.1");
		product.setStockQty(100.00);
		product.setPrice(95.99);
		em.persist(product);
		em.getTransaction().commit();
		em.close();
		
	}
}

Use the following command for compiling the code:

mvn compile

Here is the output of the compilation:

Hibernate 4.3 and JPA 2.1 Example

Use the following command for executing the code:

mvn exec:java -Dexec.mainClass="net.roseindia.AppTest" 

Here is the output of program execution:

Hibernate 4.3 and JPA 2.1 Example

In this tutorial you have learned how to write program using Hibernate 4.3.x and JPA 2.1. Now you should be able to use the Hibernate with JPA 2.1. Check more JPA 2.1 tutorials

Download the source code of the project discussed here. 

Read Complete Hibernate 4.3.x tutorial at Hibernate 4.3.x home page.