Category Archives: Hibernate

Could not load JDBC driver class [oracle.jdbc.driver.OracleDriver

I am trying to connection my java web application to the Oracle9i database.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/config/sdnext-servlet.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [oracle.jdbc.driver.OracleDriver]


Make sure you have the ojdbc14.jar in your run time classpath.

Download the same from

Happy Learning ūüôā


Hibernate framework Introduction

With continuation from my last post

If we want to master on any new technology, it requires enormous effort.  Hibernate is not an exception from that.  But, Hibernate framework is really simple to master as well as to make it use over business scenarios.  Here is the below list of benefits or advantages of Hibernate Framework,

  1. Hibernate framework is the implementation of Object-Relational Mapping technique.
  2. Easily map JAVA objects with Relational tables.
  3. Converts JAVA data types to Relational data types easily.
  4. Highly overcome the problems that originate because of Impedance mismatch.
  5. Allows developers to focus on business model rather than on database interactions.
  6. Hibernate is database portable. It supports most of the databases available in the market.
  7. Little changes in XML mapping is enough for any complex changes if required.
  8. Provides various query handling capabilities. No need to write database specific queries.
  9. Hibernate provides two level of cache.
  10. Hibernate supports Hibernate Query Language, which can be used to create object queries.
  11. Finally, Hibernate does not replace JDBC.  Rather, it overcomes the limitations of JDBC.
  • Hibernate acts as a bridge between an application and the underlying database that stores data.
  • Hibernate uses the various mapping files that represent persistent JAVA objects.
  • Hibernate maps each properties of JAVA objects to the specific columns of tables in the underlying database.


Hibernate Architecture:

It has 3 major components

  1. Object Relational Mapping
  2. Connection Management
  3. Transaction Management


Object Relational Mapping: Maps the data in Object model to the Relational Model

Connection Management: Focuses on database connections and helps us for managing the database connections.

Transaction Management: Controls various database queries and transactions. It provides built-in data querying and retrieval capabilities, which does not require us to write database specific queries.


Hibernate Database Configuration:

We need make the JAVA application and Hibernate system to work as a unit.  For that, we need to configure Hibernate with a database for each storage and retrieval of data from underlying database.  So that JAVA application can easily interact with database system with the help of Hibernate system by passing the JAVA persistence objects to and fro for storage and retrieval.

Our JAVA application may deployed in any of the following environments

  • Managed
  • Non-Managed

Managed environment refers to server-based environment where a application is managed by server containers.  Example application servers are JBOSS, Websphere, etc.,

Non-Managed environment refers to stand alone environment where application themselves need to manage everything right from connection management, transaction services, caching services, etc.,

Java application configured with Hibernate is portable in any environments.


Things needed to configure Java application with Hibernate:

  • Database connection parameters (like URL, hostname, port, db driver name, username and password)
  • Caching parameters
  • Persistence classes to manage
  • Mapping of Persistence classes to specific tables information.


Hibernate provides two configuration files:

  1.‚ÄĒa Java properties file
  2. hibernate.cfg.xml‚ÄĒan XML file.

We can use either or both of these options.  But, when we use both, hibernate.cfg.xml file overrides file.

The hibernate.cfg.xml configuration file provides various properties,

By default, Hibernate loads the hibernate.cfg.xml file and the mapping files present in the class path, and sets the properties provided in these files.

Configuration class in Hibernate

Alternatively, we can set configuration properties and load mapping files programmatically, like below,

Configuration config = new Configuration();

config.addResource( “mapping document”);


config.addClass( classname );

By default, Hibernate searches the mapping document in the class path. However, if you want to load a mapping document from a location other than the class path, you must specify the full path of the mapping file in the addResource() method.




By default, Hibernate configuration properties are set using the hibernate.cfg.xml file. You can, however, set specific properties in addition to those mentioned in the configuration file programmatically. For instance, the code

config.addResource( “mapping document”).addProperty(‚Äúhibernate.dialect‚ÄĚ,‚ÄĚorg.hibernate.dialect.MySQLDialect‚ÄĚ);

enables you to not only load a mapping document, but also add the hibernate.dialect property programmatically.

From the hibernate documentation, The org.hibernate.cfg.Configuration is meant only as an initialization-time object.   Usually an application will create a single Configuration, build a single instance of SessionFactory and then instantiate Sessions in threads servicing client requests. A new Configuration will use the properties specified in by default.

Configuration() ‚Äď default constructor

addFile(File¬†xmlFile) –¬† Read mappings from a particular XML file

addURL(URL¬†url) –¬†Read mappings from a URL

addJar(File¬†jar) –¬†Read all mappings from a jar file

addProperties(Properties¬†extraProperties) –¬†Add the given properties to ours.

buildSessionFactory() РCreate a SessionFactory using the properties and mappings in this configuration.  The SessionFactory will be immutable, so changes made to this Configuration after building the SessionFactory will not affect it.


SessionFactory is an interface that represents an immutable cache of compiled mappings for a single database specified in the hibernate.cfg.xml file.

SessionFactory is a global factory responsible for a particular database. If you have several databases, for easier startup you should use several <session-factory> configurations in several configuration files.


  • A Hibernate application will have only one SessionFactory instance that will be instantiated when the application is started.
  • SessionFactory instances are thread-safe, so they can be simultaneously accessed by multiple threads without hampering the function of the application.

Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory.

Configuration configuration = new Configuration();
configuration.setProperty("hibernate.connection.username", "admin");
configuration.setProperty("hibernate.connection.password", "admin");
configuration.setProperty("hibernate.show_sql", "true");
SessionFactory sessionFactory = configuration.buildSessionFactory();

Sample Hibernate Configuration file from Hibernate Reference Document
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
         <!-- Database connection settings -->
        <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
        <property name="connection.url">jdbc:hsqldb:hsql://localhost</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>
        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <!-- Drop and re-create the database schema on startup -->
        <property name="">update</property>
         <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>


SessionFactory has various methods

openSession() –¬†¬†Open a Session.

isClosed()–¬†Is this factory already closed?

getCache() Р Obtain direct access to the underlying cache regions.  SessionFactory represents the second level cache of data that can be reused among transactions, and controls the overall functioning of the Hibernate application.

close() – Destroy this SessionFactory and release all resources (caches, connection pools, etc).

The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping.

SessionFactory provides second level cache.  The below shows options to disable the second level cache

¬†¬†¬† <!– Disable the second-level cache¬† –>

¬† ¬†¬†¬†¬†¬†¬†<property name=”cache.provider_class”>org.hibernate.cache.NoCacheProvider</property>

Optionally maintains a second level cache of data that is reusable between transactions at a process or cluster level.



A org.hibernate.Session interface is designed to represent a single unit of work. A session represents a conversation between an application and a database. It is a non-threadsafe object that can span multiple business transactions, each of which may span multiple database transactions.

The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes.

Once all transactions associated with a session are complete, the session must be closed and discarded.

Sessions are used to persist objects, query persistent objects, and then convert persistent objects into transient objects. Hibernate provides the Session class to create and manage sessions. A SessionFactory instance can have one or more session instances to represent a particular business transaction.

A typical transaction should use the following idiom:

 Session sess = sessionfactory.openSession(); //to instantiate a Session
 Transaction tx;
 try {
     tx = sess.beginTransaction();
     //do some work
 catch (Exception e) {
     if (tx!=null) tx.rollback();
     throw e;
 finally {

If the Session throws an exception, the transaction must be rolled back and the session discarded. The internal state of the Session might not be consistent with the database after the exception occurs.

In a managed environment, the application can access the current session by calling the sessionFactory.getCurrentSession() method.

First, you can call it as many times and anywhere you like once you get hold of your org.hibernate.SessionFactory. The getCurrentSession() method always returns the “current” unit of work.


Due to the below setting, the context of a current unit of work is bound to the current Java thread that executes the application.

<!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

 Session is then bound by Hibernate to the current thread. When the transaction ends, either through commit or rollback, Hibernate automatically unbinds the org.hibernate.Session from the thread and closes it for you. If you call getCurrentSession() again, you get a new org.hibernate.Session and can start a new unit of work.

Session interface various methods, few listed below

beginTransaction() – Begin a unit of work and return the associated Transaction object.

close() – End the session by releasing the JDBC connection and cleaning up.

contains(Object object) РCheck if this instance is associated with this Session. Checks that the persistence object is in cache.

delete(Object object) РRemove a persistent instance from the datastore (database).

evict(Object object) Р Remove this instance from the session cache.

flush() РForce this session to flush.  It synchronizes persistence objects in memory with those in database. Typically used before committing a transaction and closing a session.

isConnected() – Check if the session is currently connected.

isOpen() – Check if the session is still open.

Hibernate Connection Pool

A connection pool is a cache of database connections. A Hibernate application can use a connection pool to maintain a collection of database connections when database requests are made, without having to open separate connections for each request.

Hibernate supports three connection pooling services: C3P0, Apache’s DBCP library, and Proxool.

You can configure connection pools for a Hibernate application using the options available in the hibernate.cfg.xml file.


A transaction is a group of operations that constitute a single unit of work.

If one of the operations fails, any changes made in response to other operations in the transaction are rolled back, causing the transaction to fail.

By default, Hibernate uses JDBC transactions, which are associated to a Session class and instantiated using the session.beginTransaction() method.

The Transaction class is used to group and manage operations in Hibernate.

Various methods of Transction

          Begin a new transaction.

          Flush the associated Session and end the unit of work

          Force the underlying transaction to roll back.


Object Relational Mapping – An introduction to Hibernate


What is Data Persistence?

It is a mechanism by which data stored in a file or database.  Generally, software program retrieves data from database and manipulates the same.  The changes made to data should be stored for later use.  So by Data Persistence we store the data in a database or file and enable the data to sustain even after program terminates, which can be used for later use.

Achieving Data Persistence is a great challenge.  We achieved through JDBC.  But JDBC has some limitations, especially when performing operations using complex join.

What is JDBC?

  • JAVA Database Connectivity is an Application Programming Interface (API), helps an application to connect and interact with the database.¬† We can connect to relational databases and perform database operations such as CRUD, directly from JAVA using JDBC API.
  • JDBC uses various JDBC drivers, which helps the JDBC on how to connect and interact with a particular type of database.

What are the limitations of JDBC?

  • Even for simple CRUD operations, JDBC requires developers to write extensive code.
  • Requires developers to write database specific SQL queries.¬† The SQL queries were hardcoded. It requires changes if any requirement change occurs.
  • Requires developers to convert JAVA object to relational format before we store the data in a database.
  • Requires developers to manually convert the result returned by the database to the JAVA objects, which represents business domain model.
  • JDBC code is not portable among various databases as it uses specific JDBC drivers that instruct JDBC how to connect and interact with that specific database.
  • Any changes in the underlying database, requires significant code changes.

So JDBC is not suitable for data intensive application, which does frequent update or retrieval of data objects.


Key Challenge:

Object Oriented Programming represents business domain as inter-related objects and each objects various properties to store data.  In contrast, Relational Data model represent data in tabular format composed of various rows and columns.  The mismatch in the representation of data in object-oriented programming and relational database model is called as Relational Impedance Mismatch.

More Factors that impede developers:

  • In an object-oriented programming, an Object may be equal or identical.¬† Objects are said to be Equal, if they contain same values. Objects are said to be identical if they hold the same reference or memory address of the actual object location and represent the same object.¬† In contrast, there is no separate notation for Identity and Equality in relational databases.
  • Object oriented programming support Inheritance, where as Relational databases do not. An Object inherits properties from a Parent Object class by means of Inheritance.¬† It was a great challenge to persist a very rich inheritance hierarchy of objects into the database.
  • Finally, object oriented Programming language supports Association, of course the Relational database as well.¬† Object oriented programming language supports many type of association such as one-to-one, one-to-many and many-to-many.¬† But Relational database supports using foreign key which is reference to the Primary key in another table. It does not support one-to-many or many-to-many associations.

What is Object Relational Mapping (ORM)?

ORM is a programming technique by which we overcome the challenge imposed by the mismatch representation of data between object oriented programming and relational database.  By this technique, we map a Class in object-oriented programming to a Table in Relational database.  So every instance of a class (object) represents rows in a Table, that is, each object represent one row in database.  Object properties represent columns in a database.  Once the classes in object-oriented programming mapped to tables in Relational database, we can directly persist an object into the database table easily.  No need to manually convert object into specific relational database format.

Advantages ORM:

  • Eliminates the need to convert objects into relational format.
  • Reduces coding effort highly.
  • Highly portable among various underlying databases.
  • Suitable for data-centric applications.
  • Direct query for an object from the underlying database. No need to write database specific SQL queries.



JAVA Persistence API (JPA) is a specification for ORM. It is an industry standard. It guides us to achieve data persistence in JAVA applications by mapping the persistence classes in object-oriented programming to the tables in relational database.  The mapping is achieved by means of separate XML file and distributed within application. 

Any ORM tool must comply with JPA specification and Hibernate framework does that.



I was facing the below issue when I use Oracle 9 JDBC driver along with Hibernate 3.6,


Initial SessionFactory creation oracle.jdbc.driver.OracleDatabaseMetaData.getDatabaseMajorVersion()I
Exception in thread “main” java.lang.NullPointerException
at org.hibernate.tutorial.test.EventManager.createAndStoreEvent(
at org.hibernate.tutorial.test.EventManager.main(



Switching to Oracle jdbc driver solved the problem immediately, without any configuration change requirements.


Download link:


Remember that Oracle recommends you to use 10 series drivers even if you are connecting to a 8 or 9 series database server!




Exception in thread “main” java.lang.NoClassDefFoundError: javax/persistence/EntityListeners

Exception in thread “main” java.lang.NoClassDefFoundError: javax/persistence/EntityListeners

at org.hibernate.cfg.annotations.reflection.JPAMetadataProvider.getDefaults(


at org.hibernate.cfg.Configuration.secondPassCompile(

at org.hibernate.cfg.Configuration.buildSessionFactory(

at com.saravanan.hibernate.test.HibernateBasicTestCase.main(

Caused by: java.lang.ClassNotFoundException: javax.persistence.EntityListeners

at$ Source)

at Method)

at Source)

at java.lang.ClassLoader.loadClass(Unknown Source)

at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)

at java.lang.ClassLoader.loadClass(Unknown Source)

at java.lang.ClassLoader.loadClassInternal(Unknown Source)

… 5 more




Place the JPA jar file


For example: hibernate-jpa-2.0-api-1.0.0.Final.jar

Exception in thread “main” java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory

Problem 2:


Exception in thread “main” java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory

at org.hibernate.cfg.Configuration.<clinit>(

at com.saravanan.hibernate.test.HibernateBasicTestCase.main(

Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory

at$ Source)

at Method)

at Source)

at java.lang.ClassLoader.loadClass(Unknown Source)

at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)

at java.lang.ClassLoader.loadClass(Unknown Source)





Place slf4j-api-1.5.2.jar file in the classpath

SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.

Problem 1:

SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.
SLF4J: See for
further details.
Initial SessionFactory creation failed.
java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder
Exception in thread “main” java.lang.ExceptionInInitializerError
at util.HibernateUtil.<clinit>(
at annuaire.test.TestHibernate.main(
Caused by: java.lang.NoClassDefFoundError: org/slf4j/impl/
at org.slf4j.LoggerFactory.<clinit>(
at org.hibernate.cfg.Configuration.<clinit>(
at util.HibernateUtil.<clinit>(
… 1 more


download an older version of slf4j.

I downloaded the same version of slf4j from here: and the problem is gone.

Place the slf4j-api-1.5.2-sources.jar in classpath.

Or place slf4j-log4j12-1.5.2.jar file in the classpath.