Hibernate Example on Eclipse and Oracle - Hibernate
Home » Hibernate, Tech Notes

Hibernate Example on Eclipse and Oracle

14 March 2009 20 Comments

Hibernate Tutorial explains you the details of this technology. Here is an a simple example which will help you to start your first hibernate web project on Eclipse and Oracle as database. I am not taking those free databases as example considering frequency of usage of Oracle. Below are the easy steps to be followed to make it all work. Futher you can take this example ahead with detail tutorial, or use it as your research ground to try other things in hibernate.

Create a Dynamic Web Project:

Follow the steps specified in similar tutorial Spring MVC Tutorial with Eclipse and Tomcat, just that the project name would be different. I used ‘HibernateExample’. This project will have complete folder structure created on your machine. To make it work with less effort, I added the resources forlder to the class path as shown below.

Add Resources to Libraries

Add Libraries:

You will need following libraries to make it all work. Add those to ‘..\WebContent\WEB-INF\lib’ directory.
antlr-2.7.6.jar
asm-1.5.3.jar
asm-attrs-1.5.3.jar
cglib-2.1_3.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
dom4j-1.6.1.jar
ehcache-1.2.3.jar
hibernate-3.2.5.ga.jar
jta.jar
ojdbc14.jar

Sample Code:

Below are the sample Java files, include those in /src/main/java directory. I am keeping the package default, change it as per your need. Just ensure you change all references of package, including those in xmls.

The domain object/bean class

Customer.java

import java.io.Serializable;

public class Customer implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long customerId = null;
    private String customerName;
public Long getCustomerId() {
  return customerId;
 }
public void setCustomerId(Long customerId) {
  this.customerId = customerId;
 }
public String getCustomerName() {
  return customerName;
 }
public void setCustomerName(String aCustomerName) {
  this.customerName = aCustomerName;
 }
public static long getSerialVersionUID() {
  return serialVersionUID;
 }
public boolean equals(Object candidate) {
        if (candidate == this) {
            return true;
        }
        if (candidate instanceof Customer) {
            if ((this.getCustomerName() != null &&
              ((Customer)candidate).getCustomerName() != null)) {
             return (this.getCustomerId()==
              (((Customer)candidate).getCustomerId())&&
                 this.getCustomerName().equals(
                   ((Customer)candidate).getCustomerName()));
            }
        }
        return false;
    }

public int hashCode() {
      return this.getCustomerId().intValue();
    }
}

Next is the class that interacts with database using hibernate and the domain object above.
CustomerDAO.java

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class CustomerDAO {
  private Session session = null;
 public void createSession(){
  Configuration cfg = new Configuration()
  .configure("hibernate.cfg.xml");
  SessionFactory sf = cfg.buildSessionFactory();
  this.session = sf.getCurrentSession();
 }

public Customer create(Customer newCustomer) {
     Transaction transaction = session.beginTransaction();
        session.save(newCustomer);
        transaction.commit();
        return newCustomer;
    }

public static void main(String[] args){
     Customer customer = new Customer();
     customer.setCustomerName("Hibernate Example Customer");

    System.out.println("Customer id before creation:" +
       customer.getCustomerId());
     CustomerDAO customerDAO = new CustomerDAO();
     customerDAO.createSession();
     Customer persistedCustomer = customerDAO.create(customer);
     System.out.println("Customer id after creation:" +
       persistedCustomer.getCustomerId());
    }
}

This is how the Customer object hibernate mapping will be.

 Customer.hbm.xml







    
        
	       
TAB_CUSTOMER_SEQ
	      
        

     

Next is the important configuration file. Change the database connection properties to match your Oracle database details.

hibernate.cfg.xml




	

		  org.hibernate.dialect.Oracle9Dialect
		

		  oracle.jdbc.driver.OracleDriver
		

		  jdbc:oracle:thin:@server:port:schema
		
user
password
defaultschema
false
true
false
false

		  org.hibernate.cache.NoCacheProvider
		
thread

	


In all this is how the folder structure will look like.

Hibernate Example Folder Structure

Last is the table creation in database. Use these scripts to create simple table in database and also the sequence related to it.

CREATE TABLE TAB_CUSTOMER
(
  CUSTOMER_ID  NUMBER(10)          NOT NULL,
  CUSTOMER_NAME           VARCHAR2(255)
)
CREATE SEQUENCE TAB_CUSTOMER_SEQ
  START WITH 1
  MAXVALUE 999999999999999999999999999
  MINVALUE 1
  NOCYCLE
  CACHE 20
  NOORDER;

Run the CustomerDAO (main method) and it will work to insert the customer in database.

 

More Related Posts in Hibernate, Tech Notes

20 Comments »

  • Viral said:

    Hi,
    Nice tutorial. This will be very helpful for people who wants to learn Hibernate.

  • admin said:

    Thanks Viral.

  • Jayaram said:

    This page which has simple example of Hibernate with Oracle is really helpfull for beginners to Hibernate.
    Thanks.

  • Vijay said:

    I want to know where the jar files are located.
    to try out this example
    antlr-2.7.6.jar
    asm-1.5.3.jar
    asm-attrs-1.5.3.jar
    cglib-2.1_3.jar
    commons-collections-2.1.1.jar
    commons-logging-1.0.4.jar
    dom4j-1.6.1.jar
    ehcache-1.2.3.jar
    hibernate-3.2.5.ga.jar
    jta.jar
    ojdbc14.jar

  • admin said:

    You can download these versions from Maven Repository site – http://repo1.maven.org/maven2/.

  • Gajanan said:

    Dear Admin,

    Cannot thank you enough for your this tutorial. Its a really great job. It really helps boost the confidence of a newbie to hibernate like me. It otherwise becomes a very cumbersome job for a newbie to write a hibernate tutorial by reading the documentation.

    Thanks… thanks a lot… and pls do keep it up.

  • James Do said:

    I use MySQL database and appear this error

    Exception in thread “main” org.hibernate.PropertyNotFoundException: Could not find a setter for property serialVersionUID in class my.src.Customer

    Please help me!

  • admin said:

    This property should not be in mapping xml.

  • uday said:

    this is very nice exm. its relay helpful.
    Thanks & Regard
    Uday Singh

  • Someone said:

    Hello. I have tried this tutorial but I had some errors: http://pastebin.com/usNrwD2h
    I have tried to fix them but I couldn’t ! Any ideeas what the problem might be and how to fix it?
    Thank you

  • Shambhavi said:

    I am getting this error, please help

    SEVERE: Error parsing XML: hibernate.cfg.xml(3) Document is invalid: no grammar found.
    Sep 22, 2010 2:43:45 PM org.hibernate.util.XMLHelper$ErrorLogger error
    SEVERE: Error parsing XML: hibernate.cfg.xml(3) Document root element “hibernate-configuration”, must match DOCTYPE root “null”.
    Exception in thread “main” org.hibernate.MappingException: invalid configuration
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1487)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1428)
    at main.java.CustomerDAO.createSession(CustomerDAO.java:11)
    at main.java.CustomerDAO.main(CustomerDAO.java:30)
    Caused by: org.xml.sax.SAXParseException: Document is invalid: no grammar found.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:131)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:384)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:318)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:250)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:626)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3103)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:922)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at org.dom4j.io.SAXReader.read(SAXReader.java:465)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1484)

  • Tufail Ahmed said:

    I am also getting same error, please help..

    SEVERE: Error parsing XML: hibernate.cfg.xml(3) Document is invalid: no grammar found.
    Sep 22, 2010 2:43:45 PM org.hibernate.util.XMLHelper$ErrorLogger error
    SEVERE: Error parsing XML: hibernate.cfg.xml(3) Document root element “hibernate-configuration”, must match DOCTYPE root “null”.
    Exception in thread “main” org.hibernate.MappingException: invalid configuration
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1487)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1428)
    at main.java.CustomerDAO.createSession(CustomerDAO.java:11)
    at main.java.CustomerDAO.main(CustomerDAO.java:30)
    Caused by: org.xml.sax.SAXParseException: Document is invalid: no grammar found.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:131)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:384)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:318)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:250)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:626)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3103)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:922)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at org.dom4j.io.SAXReader.read(SAXReader.java:465)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1484)

  • uma said:

    Hi

    Try adding the details regarding xml DTD as below jsut before the source code provided here for hibernate.cfg.xml file. This worked for me.

  • Dolphy Fernandes said:

    I too had the same error but I could solve it. The tutorial misses doctype tag in both hbm and config files. To solve the above problem, add the following,

    In hibernate.cfg.xml:

    In Customer.hbm.xml:

    Hope that helps!!

  • Shishir Verma said:

    All the tags in these XMLs are supposed to be in lowercase, and hence is not a tag as per the DTD. It should be used in lowercase as .

    Other tags too should be in lowercase.
    It should solve the issues like
    SEVERE: Error parsing XML: hibernate.cfg.xml(3) Document is invalid: no grammar found.

  • mon_proj said:

    Hello;
    I have to connect oracle to hibernate in eclipse for a desktop application.
    did you have an example please ?

  • Mritunjay said:

    Hey nice tutorial but i have a doubt please clerify it why does we need ti implement equals and hashcode methods for the bean customer. is it necessary or its a good practice please explain

  • Shyama said:

    We did hibernate pgming in eclipse using Mysql db.But it shows the following errors pl help us to solve it.
    log4j:WARN No appenders could be found for logger (org.hibernate.type.BasicTypeRegistry).
    log4j:WARN Please initialize the log4j system properly.

  • pratibha said:

    Nice tutorial. And the examplw worked in first go. Thanks.

  • Ankit said:

    Following error occured using eclipse indigo with sql server 2008 using hibernate 4.0:

    Jan 13, 2012 11:01:58 PM org.hibernate.annotations.common.Version
    INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
    Jan 13, 2012 11:01:58 PM org.hibernate.Version logVersion
    INFO: HHH000412: Hibernate Core {4.0.0.Final}
    Jan 13, 2012 11:01:58 PM org.hibernate.cfg.Environment
    INFO: HHH000206: hibernate.properties not found
    Jan 13, 2012 11:01:58 PM org.hibernate.cfg.Environment buildBytecodeProvider
    INFO: HHH000021: Bytecode provider name : javassist
    Jan 13, 2012 11:01:58 PM org.hibernate.cfg.Configuration configure
    INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
    Jan 13, 2012 11:01:58 PM org.hibernate.cfg.Configuration getConfigurationInputStream
    INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
    Jan 13, 2012 11:01:58 PM org.hibernate.internal.util.xml.XMLHelper$ErrorLogger error
    ERROR: HHH000197: Error parsing XML: /hibernate.cfg.xml(3) Document is invalid: no grammar found.
    Jan 13, 2012 11:01:58 PM org.hibernate.internal.util.xml.XMLHelper$ErrorLogger error
    ERROR: HHH000197: Error parsing XML: /hibernate.cfg.xml(3) Document root element “hibernate-configuration”, must match DOCTYPE root “null”.
    org.hibernate.MappingException: invalid configuration
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2005)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1922)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1901)
    at mypkg.ManyToManyRelation.main(ManyToManyRelation.java:18)
    Caused by: org.xml.sax.SAXParseException: Document is invalid: no grammar found.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at

    com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
    at org.dom4j.io.SAXReader.read(SAXReader.java:465)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2002)
    … 3 more
    invalid configuration

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.