Home  >  JPA

JPA 2 Example | Java Persistence API

By Arvind Rai, September 06, 2013
JPA is Java Persistence API. JPA provides Object Relational Mapping (ORM) in Java. JPA handles the database query, database optimization, database cache, data saving, querying. JPA covers Java Persistence API, query language, Criteria API and ORM metadata. JPA makes database handling easy. In our example, I will show you how to start with JPA step by step. We are using MySQL database, JPA 2 and using eclipse IDE.

Step-1: Configure JPA Jar Dependency

To get the Java Persistence API, we will include hibernate JPA in our classpath. Create a java project in eclipse and configure pom.xml as below.

pom.xml
<?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.concretepage</groupId>
<artifactId>jpademo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<properties>
    
  <hibernate.version>4.2.5.Final</hibernate.version>
    <mysql-connector.version>5.1.26</mysql-connector.version>
    <slf4j.version>1.7.5</slf4j.version>
    <log4j.version>1.7.5</log4j.version>
</properties>

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

     <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql-connector.version}</version>
    </dependency>
  
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${slf4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>${log4j.version}</version>
    </dependency>
</dependencies>

</project>
 
Run the pom.xml and configure eclipse classpath by the below command.
mvn eclipse:eclipse
 
Use this command in command prompt switching into your project directory.


Step-2: Create JPA Entity

Farmer.java
package com.concretepage.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="farmer")
public class Farmer {
	@Id
	@Column(name="id")
	private int id;
	@Column(name="name")
	private String name;
	@Column(name="village")
	
	private String village;
	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 String getVillage() {
		return village;
	}
	public void setVillage(String village) {
		this.village = village;
	}
}
 

Step-3: Create JPA persistence.xml

First create a folder META-INF in your classpath then create a file named persistence.xml and configure as below.

persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<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="com.concretepage">
        <description>JPA Test</description>
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>com.concretepage.entity.Farmer</class> 
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="create-drop"/>

            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/jpadb"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value=""/>
        </properties>
    </persistence-unit>
</persistence>
 
Configure your persistence-unit name, entity, database connection in persistence.xml.

Step-4: Use EntityManagerFactory and EntityManager to Run JPA Demo

To run the demo, create a main class and get Manger factory by Persistence.createEntityManagerFactory . Pass persistence-unit name as argument. Create EntityManager by EntityManagerFactory. Now run the program and check the database for inserted values.

JPADemo.java
package com.concretepage;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.concretepage.entity.Farmer;
public class JPADemo {
 	private static final EntityManagerFactory emFactory;
	static {
		   emFactory = Persistence.createEntityManagerFactory("com.concretepage");
	}
	public static EntityManager getEntityManager(){
		return emFactory.createEntityManager();
	}
	public static void main(String[] args) {
		EntityManager em = getEntityManager();	
		em.getTransaction().begin();
		
		Farmer f = new Farmer();
		f.setId(1);
		f.setName("Ram");
		f.setVillage("Dhananjaypur");
		em.persist(f);
		
		em.getTransaction().commit();
		em.clear();
		System.out.println("Done");
	}
}
 

JPA Eclipse Configuration and Demo Output

Find the eclipse configuration and data inserted into the table by our JPA program.

JPA 2 Example | Java Persistence API

Download Source Code
java-persistence-api-example.zip
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us