JPA - Getting Started - Hello World

Card Puncher Data Processing

About

A simple JPA implementation that insert an “Hello World” string in a HELLO table in a relational database.

This example uses the JPA reference implementation: Java - Eclipse Link (JPA, JAXB, Persistence Provider) against an Oracle Database.

Steps

Classpath

Maven Dependency for the Eclipselink persistence provider

<!-- JPA -->
<dependency>
	<groupId>org.eclipse.persistence</groupId>
	<artifactId>eclipselink</artifactId>
	<version>2.5.2-M1</version>
	<exclusions>
		<exclusion>
			<groupId>org.eclipse.persistence</groupId>
			<artifactId>commonj.sdo</artifactId>
		</exclusion>
	</exclusions>
</dependency>

and the jar of your database:

  • for Oracle: ojdbc6.jar

Persistence.xml

Create the persistence.xml in the META-INF directory.

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" 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">
    <persistence-unit name="PersistenceUnitName" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>HelloWorldJpa</class>
    </persistence-unit>
</persistence>

where:

  • the attribute name (PersistenceUnitName) is the id of the persistence unit and is a mandatory parameter when making a EntityManager factory
  • the transaction-type defines the application type (J2EE of JSE). The value RESOURCE_LOCAL defines a JSE application
  • the provider node defines the provider class (here it's the EclipseLink class)
  • the class node contains the entities. Here we have declared only one entity named HelloWorldJpa

Entity

The entity representing a record in the table HELLO. The mapping between the java field and the column is made thanks to the JPA annotations.

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "HELLO")
public class HelloWorldJpa implements Serializable {

    @Id
    @Column(name = "ID", unique = true, nullable = false, updatable=false)
    private String id;

    @Basic()
    @Column(name = "DESCRIPTION")
    private String Description;

    public String getId() {
        return id;
    }

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

    public String getDescription() {
        return Description;
    }

    public void setDescription(String description) {
        Description = description;
    }


}

Main

The main class that create an HelloWorldJpa Object and persists it in the database.

The persistence properties are set programmatically instead of in the persistence.xml file.

import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.eclipse.persistence.config.TargetDatabase;
import org.eclipse.persistence.logging.SessionLog;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.HashMap;
import java.util.Map;

public class Main {

    public static void main(String[] args) {

        Map props = new HashMap();


        props.put(PersistenceUnitProperties.JDBC_USER, "sh");
        props.put(PersistenceUnitProperties.JDBC_PASSWORD, "sh");
        props.put(PersistenceUnitProperties.TARGET_DATABASE, TargetDatabase.Oracle11);
        props.put(PersistenceUnitProperties.JDBC_DRIVER,"oracle.jdbc.OracleDriver");
        props.put(PersistenceUnitProperties.JDBC_URL,"jdbc:oracle:thin:@localhost:1521/pdborcl.hotitem.local");
        props.put(PersistenceUnitProperties.LOGGING_LEVEL, SessionLog.FINE_LABEL);

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersistenceUnitName", props);

        EntityManager em = emf.createEntityManager();

        HelloWorldJpa helloWorldJpa = new HelloWorldJpa();
        helloWorldJpa.setId("1");
        helloWorldJpa.setDescription("Hello Nico !");

        em.getTransaction().begin();
        // The Merge method will do a select followed by an insert
        // while the persist method will make always an insert statement
        em.merge(helloWorldJpa);
        em.getTransaction().commit();
        em.close();
        emf.close();

    }

}

Log Generated

The log generated is level dependent and was set to the CONFIG_LEVEL dynamically in the main class.

[EL Config]: metadata: 2013-12-18 13:07:02.036--ServerSession(226287566)--Thread(Thread[main,5,main])--
The access type for the persistent class [class HelloWorldJpa] is set to [FIELD].

[EL Config]: metadata: 2013-12-18 13:07:02.065--ServerSession(226287566)--Thread(Thread[main,5,main])--
The alias name for the entity class [class HelloWorldJpa] is being defaulted to: HelloWorldJpa.

[EL Info]: 2013-12-18 13:07:02.793--ServerSession(226287566)--Thread(Thread[main,5,main])--
EclipseLink, version: Eclipse Persistence Services - 2.5.2.v20131113-a7346c6

[EL Config]: connection: 2013-12-18 13:07:02.801--ServerSession(226287566)--
Connection(1300062270)--Thread(Thread[main,5,main])--connecting(DatabaseLogin(
	platform=>Oracle11Platform
	user name=> "sh"
	datasource URL=> "jdbc:oracle:thin:@localhost:1521/pdborcl.hotitem.local"
))
[EL Config]: connection: 2013-12-18 13:07:03.257--ServerSession(226287566)--Connection(258237494)--Thread(Thread[main,5,main])--
Connected: jdbc:oracle:thin:@localhost:1521/pdborcl.hotitem.local
	User: SH
	Database: Oracle  Version: Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 - 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options
	Driver: Oracle JDBC driver  Version: 11.1.0.7.0-Production

[EL Info]: connection: 2013-12-18 13:07:03.315--ServerSession(226287566)--Thread(Thread[main,5,main])
--file:/D:/svn_obiee-utility-plus/target/classes/_PersistenceUnitName_url=jdbc:oracle:thin:@localhost:1521/pdborcl.hotitem.local_user=sh login successful

[EL Fine]: sql: 2013-12-18 13:07:03.413--ServerSession(226287566)--Connection(258237494)--Thread(Thread[main,5,main])--
SELECT ID, DESCRIPTION FROM HELLO WHERE (ID = ?)
	bind => [1]

[EL Fine]: sql: 2013-12-18 13:07:03.532--ClientSession(1980913642)--Connection(258237494)--Thread(Thread[main,5,main])--
INSERT INTO HELLO (ID, DESCRIPTION) VALUES (?, ?)
	bind => [1, Hello Nico !]

[EL Config]: connection: 2013-12-18 13:07:03.541
--ServerSession(226287566)--Connection(258237494)--Thread(Thread[main,5,main])--
disconnect

[EL Info]: connection: 2013-12-18 13:07:03.542
--ServerSession(226287566)--Thread(Thread[main,5,main])--
file:/D:/svn_obiee-utility-plus/target/classes/_PersistenceUnitName_url=jdbc:oracle:thin:@localhost:1521/pdborcl.hotitem.local_user=sh logout successful

[EL Config]: connection: 2013-12-18 13:07:03.542
--ServerSession(226287566)--Connection(1300062270)--Thread(Thread[main,5,main])--
disconnect

More

Documentation / Reference





Discover More
Card Puncher Data Processing
JPA - Java Persistence API (JPA)

API The Java Persistence API is the Java API for the management of persistence and object/relational mapping for: Java EE and Java SE environments The Java Persistence consists of: The Java...



Share this page:
Follow us:
Task Runner