Hibernate Example on Eclipse and Oracle

Hibernate Tutorial explains you the details of this technology. Here is a hibernate 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.

Implementing Hibernate Example:

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.

Hibernate Example

Add Libraries:

You will need following libraries to make this hibernate example work. Add those to ‘..WebContentWEB-INFlib’ 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 in our hibernate example.

 Customer.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="Customer" table="TAB_CUSTOMER" >
        <id name="customerId" column="CUSTOMER_ID" type="long">
	      <generator class="sequence">
	        <param name="sequence">TAB_CUSTOMER_SEQ</param>
	      </generator>
        </id>
        <property  name="customerName" column ="CUSTOMER_NAME"
          insert="true" update="true" type="java.lang.String" />
     </class>
</hibernate-mapping>

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

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<property name="dialect">
		  org.hibernate.dialect.Oracle9Dialect
		</property>
		<property name="connection.driver_class">
		  oracle.jdbc.driver.OracleDriver
		</property>
		<property name="connection.url">
		  jdbc:oracle:thin:@punhjwlt27520.ad.infosys.com:1521:KYCDB
		</property>
		<property name="connection.username">kycr18</property>
		<property name="connection.password">kycr18</property>
		<property name="default_schema">kycr18</property>
		<property name="connection.autocommit">false</property>

        <property name="show_sql">true</property>
		<property name="use_outer_join">false</property>

		<property name="hibernate.cache.use_second_level_cache">false</property>
		<property name="cache.provider_class">
		  org.hibernate.cache.NoCacheProvider
		</property>

		<property name="current_session_context_class">thread</property>

		<mapping resource="Customer.hbm.xml"/>
	</session-factory>

</hibernate-configuration>

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

Hibernate Example

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. Check the database to confirm the hibernate example working.

24 Comments

  1. 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

  2. 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.

  3. 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!

  4. 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)

  5. 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)

  6. 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.

  7. 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!!

  8. 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.

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

  10. 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

  11. 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.

  12. 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

  13. Any Ideas please
    Exception in thread “main” org.hibernate.TransactionException: Could not find UserTransaction in JNDI:
    at org.hibernate.transaction.JTATransaction.(JTATransaction.java:64)
    at org.hibernate.transaction.JTATransactionFactory.createTransaction(JTATransactionFactory.java:57)
    at org.hibernate.jdbc.JDBCContext.getTransaction(JDBCContext.java:193)
    at org.hibernate.impl.SessionImpl.getTransaction(SessionImpl.java:1315)
    at org.hibernate.context.ThreadLocalSessionContext.currentSession(ThreadLocalSessionContext.java:78)
    at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:542)
    at CustomerDAO.createSession(CustomerDAO.java:13)
    at CustomerDAO.main(CustomerDAO.java:30)
    Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
    at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
    at javax.naming.InitialContext.lookup(Unknown Source)
    at org.hibernate.transaction.JTATransaction.(JTATransaction.java:60)
    … 7 more

  14. Aug 01, 2016 6:03:35 PM org.hibernate.Version logVersion
    INFO: HHH000412: Hibernate Core {5.1.0.Final}
    Aug 01, 2016 6:03:35 PM org.hibernate.cfg.Environment
    INFO: HHH000205: Loaded properties from resource hibernate.properties: {hibernate.connection.driver_class=org.h2.Driver, hibernate.service.allow_crawling=false, hibernate.dialect=org.hibernate.dialect.H2Dialect, hibernate.max_fetch_depth=5, hibernate.format_sql=true, hibernate.generate_statistics=true, hibernate.connection.username=sa, hibernate.connection.url=jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1, hibernate.bytecode.use_reflection_optimizer=false, hibernate.connection.pool_size=5}
    Aug 01, 2016 6:03:35 PM org.hibernate.cfg.Environment buildBytecodeProvider
    INFO: HHH000021: Bytecode provider name : javassist
    Aug 01, 2016 6:03:36 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager
    INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
    java.lang.NoSuchMethodError: org.hibernate.cfg.annotations.reflection.XMLContext.(Lorg/hibernate/boot/spi/ClassLoaderAccess;)V
    dbType: oracle
    username: contract
    password: contract
    java.lang.NoSuchMethodError: org.hibernate.cfg.annotations.reflection.XMLContext.(Lorg/hibernate/boot/spi/ClassLoaderAccess;)V
    Could not create SessionFactory Object

Leave a Reply

Your email address will not be published.


*