Srikanth Technologies

How to use Hibernate + Maven + Oracle in Eclipse

In this blog, I show how to create a Maven project in Eclipse that uses Hibernate to access Oracle.

Create Maven Project

First let’s create a new project using Maven in Eclipse.

I am using Eclipse Mars. However the steps remain same even in other versions of Eclipse.

Here are the steps to create a new Maven project.

  1. Select File -> New -> Maven Project

    As we don’t want to use any predefined Artifacts of Maven, we select Create a simple project (skip archetype selection) checkbox (as shown in above picture).

  2. Enter the following details in New Maven Project window as shown in picture below.

    Group Id com.st
    Artifact Idhibernate
    Name Hibernate Demo
    Description Hibernate Demo Project

    The rest of the details are left unchanged.

    This creates a project with name hibernate as Artifact Id becomes project name. As it is a Maven project, we see the following directory structure.

    POM file contains information about project and its dependencies. Here is POM file as of now.

    <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.st</groupId>
      <artifactId>hibernate</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <name>Hibernate Demo</name>
      <description>Hibernate Demo Project</description>
    </project>
    

    Modify POM file

    In order to use Hibernate we need to add a dependency for Hibernate in POM file.

    As you notice in the diagram, Maven by default uses Java 1.5. So, we need to add a plugin in POM file to change it to Java 1.8. Of course this is required only if you are planning to use any features of Java 6 or above.

    Unfortunately there is no Maven project for Oracle JDBC driver. So, we need to get it from local system using another dependency that refers to a file in the current system path. For this you need to find out where is OJDBC6.JAR, which is JDBC driver for Oracle Database 11g.

    Here is new POM.XML file with all required changes.

    <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.st</groupId>
    	<artifactId>hibernate</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<name>Hibernate Demo</name>
    	<description>Hibernate Demo Project</description>
    	<dependencies>
    		<dependency>
    			<groupId>org.hibernate</groupId>
    			<artifactId>hibernate-core</artifactId>
    			<version>5.1.0.Final</version>
    		</dependency>
    		<dependency>
    			<groupId>com.oracle</groupId>
    			<artifactId>ojdbc6</artifactId>
    			<version>11.0</version>
    			<scope>system</scope>
    			<systemPath>d:/software/java/ojdbc6.jar</systemPath>
    		</dependency>
    	</dependencies>
    
    	<build>
    		<finalName>hbdemo</finalName>
    		<plugins>
    			<plugin>
    				<groupId>org.apache.maven.plugins</groupId>
    				<artifactId>maven-compiler-plugin</artifactId>
    				<version>3.3</version>
    				<configuration>
    					<source>1.8</source>
    					<target>1.8</target>
    				</configuration>
    			</plugin>
    		</plugins>
    	</build>
    </project>
    

    As you save POM file, Maven will download required .jar files for the mentioned projects. Maven stores downloaded .jar files in local repository, which is c:\users\\.m2\repository folder .

    This project uses hibernate-core as one of the dependencies. The other one is not to be downloaded as it is present in the current system. Notice elements <scope> and <scopePath> in dependency entry.

    We added maven-compile-plugin in the <build> section of POM file to inform Maven that we want to use Java 1.8.

    Note:

    It is better to update project after you modify POM file by right clicking on project and select Maven -> Update Project. Select project hibernate in Update Maven Project window and click on Ok. That should fix all sync problems related to project.

    Add Classes and Configuration files

    In order to use Hibernate, we need to add the following components. All these components are placed in src/main/java folder.

    Let’s create hibernate configuration file (hibernate.cfg.xml) where we provide information about how to connect to Oracle from Hibernate.

    <?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="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    		<property name="hibernate.connection.password">hr</property>
    		<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
    		<property name="hibernate.connection.username">hr</property>
    		<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
    		<property name="hibernate.show_sql">true</property>
    		<property name="hibernate.hbm2ddl.auto">none</property>
    		<mapping resource="Job.hbm.xml" /> 
    	</session-factory>
    </hibernate-configuration>
    
    

    We need to create mapping file to map Job class to Jobs table in Oracle. Here is job.hbm.xml.

    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
        <class name="Job" table="JOBS">
            <id name="id" type="java.lang.String" column="JOB_ID">
                <generator class="assigned" />
            </id>
            <property name="title" type="java.lang.String"  column="JOB_TITLE" />
        </class>
    </hibernate-mapping>
    
    Create Job class that is being mapped to Jobs table as follows:

    public class Job {
    	String id,title;
    	public String getId() {
    		return id;
    	}
    	public void setId(String id) {
    		this.id = id;
    	}
    	public String getTitle() {
    		return title;
    	}
       	public void setTitle(String title) {
    		this.title = title;
    	}
    }
    

    Now, let’s write code to list jobs from Jobs table using Hibernate as follows:

    import java.util.List;
    
    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    public class ListJobs {
    	public static void main(String[] args) throws Exception {
    		Configuration c = new Configuration();
    		c.configure(); // loads hibernate.cfg.xml
    
    		SessionFactory sf = c.buildSessionFactory();
    		Session s = sf.openSession();
    		Query q = s.createQuery("from Job");
    
    		for (Job j : (List<Job>) q.list()) {
    			System.out.println(j.getTitle());
    		}
    
    		s.close();
    		sf.close();
    	}
    }
    

    The following picture shows project structure after all components are placed.

    As all is ready, go to ListJobs.java and run it to get the list of job titles from Jobs table.

    If all is well, you will see list of job titles.