In this Hibernate tutorial, I will guide you how to configure Hibernate framework to work with Oracle database. The code examples below are tested with Hibernate 5 and Oracle Express database 18c. Here are the steps:

 

1. Use JDBC driver for Oracle database

A JDBC driver for Oracle must be present in your project’s classpath. Click here to download Oracle Database JDBC driver. Choose the version according to your Oracle database installation (you must have an account in Oracle website to download. Sign up is free).

Extract the downloaded archive file and add the ojdbc8.jar to the project’s classpath, e.g. in Eclipse IDE:

ojdbc classpath Eclipse

In case you use Maven, add the following dependency into the pom.xml file:

<dependency>
	<groupId>com.oracle</groupId>
	<artifactId>ojdbc8</artifactId>
	<version>1.0</version>
	<scope>system</scope>
	<systemPath>d:/Path/To/Oracle/ojdbc8-full/ojdbc8.jar</systemPath>
</dependency>
Due to Oracle’s license restriction, you can’t download the driver directly from Maven’s repository, so you have to use dependency like that.


2. Specify database connection properties

If you use hibernate.cfg.xml file, specify connection properties for Oracle database as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>      
  <session-factory>
    <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
    <property name="connection.url">jdbc:oracle:thin:@localhost:1521:dbname</property>
    <property name="connection.username">user</property>
    <property name="connection.password">pass</property>
    <property name="dialect">org.hibernate.dialect.Oracle8iDialect</property>
    
    <property name="show_sql">true</property>
        
    <mapping class="package.ModelClass1" />
    <mapping class="package.ModelClass2" />
    <mapping class="package.ModelClass3" />
     
  </session-factory>
</hibernate-configuration>
Remember that the hibernate.cfg.xml file must be put in the src/main/resources folder of your project.



In case you use JPA/Hibernate, specify database connection properties in the persistence.xml file like this:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
          http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
	version="2.1">
	
	<persistence-unit name="CustomerDB">
		<properties>
			<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:dbname" />
			<property name="javax.persistence.jdbc.user" value="user" />
			<property name="javax.persistence.jdbc.password" value="pass" />
			<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver" />
			<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle8iDialect" />
			
		</properties>
	</persistence-unit>
</persistence>
Note that the persistence.xml file must be in the src/main/resources/META-INF folder.

 

3. Create Sequence in Oracle database

Since Oracle doesn’t have auto-increment feature for primary key, you must use sequence instead. Use the following annotation for mapping the primary key field in a model class:

@GeneratedValue(strategy = GenerationType.SEQUENCE)
For example, the Customer class that maps to the Customers table in the database:

@Entity
@Table(name = "CUSTOMERS")
public class Customer {
	private Integer id;
	private String name;
	private String email;


	@Id
	@Column(name = "CUSTOMER_ID")
	@GeneratedValue(strategy = GenerationType.SEQUENCE)
	public Integer getId() {
		return id;
	}


	// constructors, getters and setters go here...
}
In this case, Hibernate will look for the sequence named HIBERNATE_SEQUENCE, so you need to create such a sequence in the database, using the following statement:

CREATE SEQUENCE "HIBERNATE_SEQUENCE" MINVALUE 1 MAXVALUE 100000 INCREMENT BY 1 START WITH 1;
If you want to use another sequence name, use the @SequenceGenerator annotation as follows:

@Id
@Column(name = "CUSTOMER_ID")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "c_generator")
@SequenceGenerator(name = "c_generator", sequenceName = "CUSTOMER_SEQUENCE")

public Integer getId() {
	return id;
}
Then create the sequence in the database accordingly:

CREATE SEQUENCE "CUSTOMER_SEQUENCE" MINVALUE 1 MAXVALUE 100000 INCREMENT BY 1 START WITH 1
You can use SQLPlus or SQL Developer tool to create the sequence.

 

4. Hibernate Example Program

For your reference, the following example program uses Hibernate to persist a Customer object to the Oracle database:

package net.codejava;
 
 import org.hibernate.*;
 import org.hibernate.boot.*;
 
 public class HibernateOracleTestXML {
 
 	public static void main(String[] args) {
 		final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
 		        .configure() // configures settings from hibernate.cfg.xml
 		        .build();
 		try {
 		    SessionFactory factory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
 		    Session session = factory.openSession();
 		    Transaction transaction = session.beginTransaction();
 		    
 		    Customer customer = new Customer("Alexander", "alexander@gmail.com");
 		    
 		    session.save(customer);
 		    
 		    transaction.commit();
 		    
 		    session.close();
 		    factory.close();
 		   
 		} catch (Exception ex) {
 		    StandardServiceRegistryBuilder.destroy(registry);
 		}
 	}
 
 }
In case you want to use JPA with Hibernate, here’s another sample program:

package net.codejava;

import javax.persistence.*;

public class JpaOracleTest {

	public static void main(String[] args) {
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("CustomerDB");
		EntityManager entityManager = factory.createEntityManager();
		
		entityManager.getTransaction().begin();;
		
		Customer customer = new Customer("Nam Ha Minh", "namhm@oracle.com");
		entityManager.persist(customer);
		
		entityManager.getTransaction().commit();
		
		entityManager.close();
		factory.close();
	}

}
As you can see, code remains the same for different databases. So to use Hibernate with Oracle database, you need to use proper JDBC driver, connection properties and create sequence.

 

Some Notes for Hibernate and Oracle database:

If somehow Hibernate inserts negative value for the ID column, you must specify allocation size for the sequence like this:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "cgen")
@SequenceGenerator(name = "cgen", sequenceName = "CUSTOMER_SEQUENCE", allocationSize = 1)
public Integer getId() {
	return id;
}
The value of the allocation size attribute be as same as the value of the “increment by” field of the sequence in Oracle database.

If the database table uses trigger to automatically insert values for the ID column, and the Hibernate’s SequenceGenerator doesn’t work somehow, try this solution:

@Id
@GeneratedValue(generator = "incrementor")
@GenericGenerator(name = "incrementor", strategy = "increment")
public Integer getId() {
	return id;
}
 

You can also watch the video version here:

 

Other Hibernate Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment

   


Comments 

#2amir hussain2021-05-06 06:38
too good tutorial It is more readable and learner and advance purpose very good
Quote
#1mivchal2020-11-01 15:03
Great tutorial. Thanks so much!
Quote