spring & hibernate

20
Spring and Hibernate Author: Santosh Kumar Kar [email protected] Spring Part - 3

Upload: santosh-kumar-kar

Post on 19-May-2015

7.571 views

Category:

Technology


0 download

TRANSCRIPT

Page 2: Spring & hibernate

Course Contents

• Who This Tutor Is For• Introduction• Do you recall Hibernate?• Why to Integrate Hibernate with Spring• Integrating Hibernate with Spring

• Step 1: Set Hibernate Libraries in classpath• Step 2: Declare a bean in Spring Config file for Hibernate Session Factory• Step 3: Inject session factory into Hibernate template.• Step 4: Inject hibernate template into DAO classes.• Step 5: Define the property HibernateTemplate in each DAO classes• Step 6: Use hibernate Queries through Hibernate Template object in DAO.

• HibernateDaoSupport• Using Hibernate 3 contextual sessions• Source code download links

Page 3: Spring & hibernate

Who This Tutor Is For?After going through this session, you will understand the Spring and Hibernate integration. Also you can know how spring provides support to use Hibernate features with Spring framework. You should have basic understanding on Spring Core parts, Spring IOC (dependency injection). If you are new to Spring, I would suggest you to refer my Spring part -1 (Beginning of Spring) before going through this session. As well you must know the Hibernate Architecture and it’s features before going through this tutor. You can also visit my Spring part-2 (Spring and Database) to know how one can use Spring with basic data connection. You can download the source codes of the examples given in this tutor from Download Links available at http://springs-download.blogspot.com/

Good Reading…

Author,Santosh

Page 4: Spring & hibernate

In Spring part-1, we had the basic understanding on using Spring and the use of DI (Dependency Injection) and in part-2 the Spring and DB connection. For all the parts of Spring, you can visit http://javacompanionbysantosh.blogspot.com

In this tutor, Spring part-3, we will see the interaction with Hibernate in Spring.

Spring comes with a family of data access frameworks that integrate with a variety of data access technologies. You may use direct JDBC, iBATIS, or an object relational mapping (ORM) framework like Hibernate to persist your data. Spring supports all of these persistence mechanisms.

Introduction:

Page 5: Spring & hibernate

Do you recall Hibernate?Hibernate is an open source project whose purpose is to make it easy to integrate relational data into Java programs. This is done through the use of XML mapping files, which associate Java classes with database tables.

Hibernate provides basic mapping capabilities. It also includes several other object/relational mapping (ORM) capabilities, including:• An enhanced, object-based SQL variant for retrieving data, known as Hibernate

Query Language (HQL).• Automated processes to synchronize objects with their database equivalents.• Built-in database connection pooling, including three opensource variants.• Transactional capabilities that can work both stand-alone or with existing Java

Transaction API (JTA) implementations.

The goal of Hibernate is to allow object-oriented developers to incorporate persistence into their programs with a minimum of effort.

Page 6: Spring & hibernate

Why to Integrate Hibernate with SpringSpring Integrates very well with Hibernate. If someone asks why do we need to integrate hibernate in Spring? Yes, there are benefits.

• The very first benefit is the Spring framework itself. The IoC container makes configuring data sources, transaction managers, and DAOs easy.

• It manages the Hibernate SessionFactory as a singleton – a small but surprisingly annoying task that must be implemented manually when using Hibernate alone.

• It offers a transaction system of its own, which is aspectoriented and thus configurable, either through Spring AOP or Java-5 annotations. Either of these are generally much easier than working with Hibernate’s transaction API.

• Transaction management becomes nearly invisible for many applications, and where it’s visible, it’s still pretty easy.

• You integrate more easily with other standards and frameworks.

Page 7: Spring & hibernate

Integrating Hibernate with SpringA typical Hibernate application uses the Hibernate Libraries, configures its SessionFactory using a properties file or an XML file, use hibernate session etc. Now let’s discuss the steps we must follow while integrating Hibernate with Spring.

Step 1: Set Hibernate Libraries in classpath.

Step 2: Declare a bean in Spring Config file for Hibernate Session Factory.

Step 3: Inject session factory into Hibernate template.

Step 4: Inject hibernate template into DAO classes.

Step 5: Define the property HibernateTemplate in each DAO classes.

Step 6: Use hibernate Queries through Hibernate Template object in DAO.

Let’s discuss all these steps one by one.

Page 8: Spring & hibernate

Step 1: Set Hibernate Libraries in classpath

To integrate Hibernate with Spring, you need the hibernate libraries along with Spring.

So the first step should be downloading all the necessary library jars for Hibernate and set those jars into the project classpath just like you already have set the Spring libraries..

Page 9: Spring & hibernate

A typical Hibernate application uses the Hibernate Libraries, configures its SessionFactory using a properties file or an XML file, use hibernate session etc. Now let’s discuss the steps we must follow while integrating Hibernate with Spring.

A typical Hibernate application configures its SessionFactory using a properties file or an XML file.

First, we start treating that session factory as a Spring bean.

• Declare it as a Spring <bean> and instantiate it using a Spring ApplicationContext.

• Configure it using Spring <property>s, and this removes the need for a hibernate.cfg.xml or hibernate.properties file.

• Spring dependency injection – and possibly autowiring – make short work of this sort of configuration task.

• Hibernate object/relational mapping files are included as usual.

Step 2: Declare a bean in Spring Config file for Hibernate Session Factory

Page 10: Spring & hibernate

We are not discussing more on different datasource types. You can visit ourSpring part-2 section to know more on declaring datasources.

All hbm files must be mapped here...

Hibernate.dialect -> declare dialect types according to your database.

In our example, we do use 2 .hbm files: Employee.hbm.xml & Department.hbm.xml

The databse is MySql and using the driver based datasource in Spring.

Remember, here the session factory class used is : LocalSessionFactoryBean.

Datasource is injected into SessionFactory

Page 11: Spring & hibernate

Step 3: Inject session factory into Hibernate template.In step 1, we declared the session factory.

In step 2 here, we are injecting that session factory into Hibernate Template. The hibernate template class is: org.springframework.orm.hibernate3.HibernateTemplate

Step 4: Inject hibernate template into DAO classes.

Observe, we have declared the bean MyHibernateTemplate in Step 3.

MyHibernateTemplate is now injected into the DAO classes such as org.santosh.dao.EmployeeDao and org.santosh.dao.DepartmentDao.

Page 12: Spring & hibernate

Step 5: Define the property HibernateTemplate in each DAO classes

Import the class org.springframework.orm.hibernate3.HibernateTemplate. The setter method is required as we inject the hibernateTemplate into the DAO class in step 4.

One of the responsibilities of HibernateTemplate is to manage Hibernate Sessions. This involves opening and closing sessions as well as ensuring one session per transaction. Without HibernateTemplate, you’d have no choice but to clutter your DAOs with boilerplate session management code.

Page 13: Spring & hibernate

Step 6: Use hibernate Queries through Hibernate Template object in DAO.

In Hibernate we were using the methods such as session.get(…), session.load(…), session.save(…), session.saveOrUpdate(…), session.delete(…) etc. All such methods are now used using hibernatetemplate. For example we use getHibernateTemplate().get(Employee.class, id) which reattach the Employee object from DB.

Page 14: Spring & hibernate

So far, the configuration of DAO class (e.g. EmployeeDao or DepartmentDao) involves four beans. • The data source is wired into the session factory bean through LocalSessionFactoryBean • The session factory bean is wired into the HibernateTemplate. • Finally, the HibernateTemplate is wired into DAO (e.g. EmployeeDao or DepartmentDao), where it is

used to access the database.

To simplify things slightly, Spring offers HibernateDaoSupport, a convenience DAO support class, that enables you to wire a session factory bean directly into the DAO class. Under the covers, HibernateDaoSupport creates a HibernateTemplate that the DAO can use.

So the only thing you1. Extend the class HibernateDaoSupport in each of the DAO class.2. Remove the property HibernateTemplate as it is already provided in HibernateDaoSupport

class.

The rest of the code will remain unchanged.

Now lets change the EmployeeDao class and implement the HibernateDaoSupport.

HibernateDaoSupport

Page 15: Spring & hibernate

Extended HibernateDaoSupport

Ignore and don’t use this in any of your DAO class because you extends HibernateDaoSupport and so this class had already done this for you.

Simply use the methods with getHibernateTemplate() method as you were using session.get(), session.load() etc. in hibernate

No changes in the spring configuration XML

Page 16: Spring & hibernate

Using Hibernate 3 contextual sessions

As we saw that one of the responsibilities of HibernateTemplate is to manage Hibernate Sessions. This involves opening and closing sessions as well as ensuring one session per transaction. But the HibernateTemplate is coupled to the Spring Framework. So some developers may find such Spring’s intrusion undesirable to use in the DAO class so instead of using the HibernateTemplate in DAO, they prefer to use the HibernateSession in that place.

So Hibernate 3 provides the cotextual session where Hibernate manages one session per transaction so there is no need to use the Hibernte template. So use HibernateSession without coupling your DAO class fully with Spring.

To implement the contextual session in Hibernate 3, you need to inject sessionFactory in place of HibernateTemplate in Spring configuration file.

No hibernateTemplate, uses SessionFactory

Page 17: Spring & hibernate

Writing DAO class

Injected SessionFactory (not HibernateTemplate)

Uses Hibernate session from SessionFactory

Page 18: Spring & hibernate

End of Part-3In part – 1 we learned the basics of Spring. And in part-2 we saw how we can work with Databases in Spring, in part-3 we discussed the integration of Hibernate with Spring.

In further parts we will see,

Part – 4 : Spring - Managing Database Transactionsat http://javacompanionbysantosh.blogspot.com/2011/10/managing-transactions-in-spring.html

Part – 5 : Spring - Securityat http://javacompanionbysantosh.blogspot.com/2011/10/spring-security.html

Part – 6 : Spring AOPat http://javacompanionbysantosh.blogspot.com/2011/10/spring-aop.html

Part – 7 : Spring MVCat http://javacompanionbysantosh.blogspot.com/2011/10/spring-mvc.html

Page 20: Spring & hibernate

Please write to:[email protected]

Do you have Questions ?