Srikanth Technologies

JPA + Oracle Database 19c

In this blog, we develop a Java SE application that uses JPA (Java Persistence API) to talk to Oracle Database 19c. In fact, this application works with any version of Oracle Database from version 12c.

JPA internally uses Hibernate as JPA provider.

Watch my video tutorial on How to use JPA with Oracle Database 19c.

Create Maven Project

Create a new Maven project using Eclipse.

Select proper workspace location and then turn on Use default Workspace location checkbox.

Make sure to select Create a simple project (skip archetype selection) checkbox also.

Click on Next.

In the next window, provide the following details regarding your project: Click on Finish button to create maven project.

POM.XML

Open POM.XML and provide the following dependencies to use Oracle JDBC Driver and Hibernate as JPA provider.

Add properties to change Java version to 20. We must change default Java version (1.5) of maven project to use new features of Java 20.

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.st</groupId>
  <artifactId>jpaoracle</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>jpaoracle</name>
  
  <dependencies>
        <dependency>
	        <groupId>com.oracle.database.jdbc</groupId>
			<artifactId>ojdbc10</artifactId>
			<version>19.21.0.0</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>5.6.0.Final</version>
		</dependency>

	</dependencies>
	
	<properties>
		<maven.compiler.source>20</maven.compiler.source>
		<maven.compiler.target>20</maven.compiler.target>
	</properties>
</project>

persistence.xml

Create persistence.xml file in src/main/resources/META-INF folder.

Create META-INF folder first and then place persistence.xml.

We are connecting to Oracle database XEPDB1, which is PDB database in Oracle Database 19c. If you are not familiar with PDB and CDB databases in Oracle, please check my blog on How to connect to Oracle XEPDB1 database.

<?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="oracle" transaction-type="RESOURCE_LOCAL">
		<!-- Persistence provider -->
		<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
		<!-- domain classes -->
		<class>entities.Course</class>
		<exclude-unlisted-classes>true</exclude-unlisted-classes>
		<properties>
			<property name="javax.persistence.jdbc.driver"
				value="oracle.jdbc.driver.OracleDriver" />
			<property name="javax.persistence.jdbc.url"
				value="jdbc:oracle:thin:@localhost:1521/xepdb1" />
			<property name="javax.persistence.jdbc.user" value="demo" />
			<property name="javax.persistence.jdbc.password" value="demo" />
			<property name="hibernate.dialect"
				value="org.hibernate.dialect.Oracle12cDialect" />
			<property name="hibernate.hbm2ddl.auto" value="update" />
			<property name="hibernate.show_sql" value="true" />
			<property name="hibernate.format_sql" value="true" />
		</properties>
	</persistence-unit>
</persistence>

Course.java

Now we create entity Course with just three attributes - id, title, fee. Place this file in src/main/java folder under package entities.

package entities;

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 = "courses")
public class Course {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int id;

	@Column(length = 20, nullable = false)
	private String title;
	
	@Column(nullable = false)
	private int fee;

	public int getId() {
		return id;
	}

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

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public int getFee() {
		return fee;
	}

	public void setFee(int fee) {
		this.fee = fee;
	}
}

AddCourse.java

The following program creates an object of Course entity and persists that object using EntityManager.

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import entities.Course;

public class AddCourse {
	public static void main(String[] args) {
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("oracle");
		EntityManager em = emf.createEntityManager();

		Course c = new Course();
		c.setTitle("JPA using Hibernate");
		c.setFee(10000);

		em.getTransaction().begin();   // must begin a transaction
		em.persist(c); // will eventually results in INSERT command
		em.getTransaction().commit();  // commit transaction 
		em.close();
	}
}

When you run the above program, if table COURSES is not found, JPA creates the table as follows:

    create table courses (
        id number(10,0) generated as identity,
        fee number(10,0) not null,
        title varchar2(20 char) not null,
        primary key (id)
    )
JPA writes insert command as follows to insert a row into COURSES table.

 insert into courses
        (id, fee, title) 
 values
        (default, ?, ?)

ListCourses.java

The following program is used to display all courses from COURSES table.

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import entities.Course;

public class ListCourses {
	public static void main(String[] args) {
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("oracle");
		EntityManager em = emf.createEntityManager();

		var query = em.createQuery("from Course", Course.class);  // JPQL
		var courses  = query.getResultList();
		
		for (var c : courses) {
			System.out.printf("%-20s  %d\n", c.getTitle(), c.getFee());
		}

		em.close();
		emf.close();
	}
}
When you run the above program, JPA (Hibernate) writes the following SQL query to retrieve rows from COURSES table.

    select
        course0_.id as id1_0_,
        course0_.fee as fee2_0_,
        course0_.title as title3_0_ 
    from
        courses course0_

Srikanth Pragada