Tag Archives: Hibernate

org.hibernate.HibernateException: No Session found for current thread

I was integrating the Spring and Hibernate on a web application. While do so, I end up with the hibernate exception as follows,

org.hibernate.HibernateException: No Session found for current thread

Solution

First we need to understand that the getCurrentSession() only makes sense inside a scope of transaction. We need to declare an appropriate transaction manager, demarcate boundaries of transaction and perform data access inside it. For example, as follows:

<tx:annotation-driven transaction-manager="hibernateTransactionManager"></tx:annotation-driven>

<bean class="org.springframework.orm.hibernate4.HibernateTransactionManager" id="hibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<list>
<value>com.saravanansivaji.model.Employee</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto} </prop>
</props>
</property>
</bean>

<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property name="driverClassName" value="${database.driver}"></property>
<property name="url" value="${database.url}"></property>
<property name="username" value="${database.user}"></property>
<property name="password" value="${database.password}"></property>
</bean>

At the service and DAO classes, the getSession() method only makes sense inside a scope of transaction, If you are trying to get sessionFactory.getCurrentSession() without defining your class in transactional scope then you will get above exception because getCurrentSession() can be use only in transactional scope. Please make your class transaction using @Transactional annnotation


@Service("employeeService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeDao employeeDao;

@Override
@Transactional(readOnly = false)
public List listEmployees() {
return employeeDao.listEmployees();
}
}

And from my DAO class EmployeeDao.java

public List listEmployees() {
try {
return (List) sessionFactory.getCurrentSession().createCriteria(Employee.class).list();
}catch(Exception e) {
System.out.println(e);
return null;
}
}

only looks for @Transactional on beans in the same application context it is defined in. This means that, if you put in a WebApplicationContext for a DispatcherServlet, it only checks for @Transactional beans in your controllers, and not your services.

Advertisements

nested exception is java.lang.NoClassDefFoundError: org/springframework/transaction/interceptor/TransactionInterceptor


SEVERE: Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/config/sdnext-servlet.xml]; nested exception is java.lang.NoClassDefFoundError: org/springframework/transaction/interceptor/TransactionInterceptor
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:412)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:131)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:598)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:661)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:517)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:458)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NoClassDefFoundError: org/springframework/transaction/interceptor/TransactionInterceptor
at org.springframework.transaction.config.AnnotationDrivenBeanDefinitionParser$AopAutoProxyConfigurer.configureAutoProxyCreator(AnnotationDrivenBeanDefinitionParser.java:126)
at org.springframework.transaction.config.AnnotationDrivenBeanDefinitionParser.parse(AnnotationDrivenBeanDefinitionParser.java:84)
at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:73)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1435)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1425)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:184)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:140)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:111)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390)
... 35 more

Oct 12, 2014 11:02:51 PM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/config/sdnext-servlet.xml]; nested exception is java.lang.NoClassDefFoundError: org/springframework/transaction/interceptor/TransactionInterceptor
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:412)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:131)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:598)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:661)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:517)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:458)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NoClassDefFoundError: org/springframework/transaction/interceptor/TransactionInterceptor
at org.springframework.transaction.config.AnnotationDrivenBeanDefinitionParser$AopAutoProxyConfigurer.configureAutoProxyCreator(AnnotationDrivenBeanDefinitionParser.java:126)
at org.springframework.transaction.config.AnnotationDrivenBeanDefinitionParser.parse(AnnotationDrivenBeanDefinitionParser.java:84)
at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:73)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1435)
at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1425)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:184)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:140)
at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:111)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390)
... 35 more

Solution

First, You need to check your runtime classpath (i.e. WEB-INF/lib) for spring-tx-…jar

Next, add aopalliance-1.0.jar or com.springsource.org.aopalliance-1.0.0.jar in the classpath solves the problem.

https://www.google.co.in/#q=download+latest+aopalliance+jar

Happy Learning ūüôā

Hibernate framework Introduction

With continuation from my last post

https://technicalrecyclebin.wordpress.com/2012/10/19/object-relational-mapping-an-introduction-to-hibernate/

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. hibernate.properties‚ÄĒ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 hibernate.properties 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”);

or

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 hibernate.properties 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.

org.hibernate.SessionFactory

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.addClass(com.saravanan.hibernate.Employee.class);
configuration.setProperty("hibernate.dialect","org.hibernate.dialect.DerbyDialect");
configuration.setProperty("hibernate.connection.url","jdbc:derby://localhost:1527/myDB");
configuration.setProperty("hibernate.connection.username", "admin");
configuration.setProperty("hibernate.connection.driver_class","org.apache.derby.jdbc.ClientDriver");
configuration.setProperty("hibernate.connection.password", "admin");
configuration.setProperty("hibernate.transaction.factory_class","org.hibernate.transaction.JDBCTransactionFactory");
configuration.setProperty("hibernate.current_session_context_class","thread");
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"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 <hibernate-configuration>
     <session-factory>
         <!-- 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="hbm2ddl.auto">update</property>
         <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>
     </session-factory>
 </hibernate-configuration>

 

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.

 

org.hibernate.Session

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
     ...
     tx.commit();
 }
 catch (Exception e) {
     if (tx!=null) tx.rollback();
     throw e;
 }
 finally {
     sess.close();
 }
 

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.

org.hibernate.Transaction

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()
          Begin a new transaction.

commit()
          Flush the associated Session and end the unit of work

rollback()
          Force the underlying transaction to roll back.

 

Object Relational Mapping – An introduction to Hibernate

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.