Last Updated on 04 October 2019   |   Print Email
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:In case you use Maven, add the following dependency into the pom.xml file:
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:
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 @SequenceGeneratorannotation as follows:
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 Customerobject 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:
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 SequenceGeneratordoesn’t work somehow, try this solution:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments