Spring Hibernate Integration

AID: 2911
  • Status: Published

4010 points

  • Byrajkumar_pb
  • TypeTutorial
  • Posted on2010-04-21 at 07:59:35
Awards
  • Community Pick
Hi,
   When I first started to learn Hibernate I found it pretty easy, but integrating it with Spring took me around 2 weeks. Not pretty cool. So I came up with the idea of writing this article which guides you simply towards the integration.

NOTE : This article assumes that you've a basic knowledge in Spring so that I don't need to start from scratch.


Its a five step process :
1. Create a hibernate configuration file
2. Create a mapping file for each DB
3. Write the POJO class
4. Call the Session Factory to access DB using Hibernate
5. Controller to finish the course

1. Create a hibernate configuration file

It's pretty common to write a hibernate-cfg.xml file, but due to the extreme flexibility of Spring, we dont need to write them all. It is completely customised so easy to write. A Sample hibernate context file is shown below. The file itself a self explained one.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
			http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

	<!--
		========================= RESOURCE DEFINITIONS
		=========================
	-->

	<!--
		Configurer that replaces ${...} placeholders with values from a
		properties file
	-->
	<!--
		(in this case, JDBC-related settings for the dataSource definition
		below)
	-->
	<context:property-placeholder location="classpath:jdbc.properties" />

	<!--
		Uses Apache Commons DBCP for connection pooling. See Commons DBCP
		documentation for the required JAR files. Alternatively you can use
		another connection pool such as C3P0, similarly configured using
		Spring.
	-->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
		p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" />

	<!-- Hibernate SessionFactory -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
		p:dataSource-ref="dataSource" p:mappingResources="dbtables.hbm.xml">
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
			</props>
		</property>
		<property name="eventListeners">
			<map>
				<entry key="merge">
					<bean
						class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener" />
				</entry>
			</map>
		</property>
	</bean>

	<!--
		Transaction manager for a single Hibernate SessionFactory (alternative
		to JTA)
	-->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager"
		p:sessionFactory-ref="sessionFactory" />

	<!--
		========================= BUSINESS OBJECT DEFINITIONS
		=========================
	-->

	<!--
		Activates various annotations to be detected in bean classes: Spring's
		@Required and @Autowired, as well as JSR 250's @Resource.
	-->
	<context:annotation-config />

	<!--
		Instruct Spring to perform declarative transaction management
		automatically on annotated classes.
	-->
	<tx:annotation-driven />

	<!--
		Exporter that exposes the Hibernate statistics service via JMX.
		Autodetects the service MBean, using its bean name as JMX object name.
	-->
	<context:mbean-export />

	<!--
		Project's central data access object: Hibernate implementation
	-->
	<bean id="login" class="org.Spring.project.service.ILoginImpl" />
</beans>
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:

Select allOpen in new window



Simple isn't it. The code itself self-descriptive and explains each and every line of code.
Hopefully, nothing more to say.

2. Create a mapping file for each DB

Now let's start to write a mapping file. Mapping file is nothing but a XML file which maps the tables to the POJO (or) bean files, so that we can use the bean to process the DB instead of writing tedious SQL queries and large java code. I think this is what ORM's are for.
The sample hbm.xml file is (hbm -> Hibernate Mapping File)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
		"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!--
  - Mapping file for the Hibernate implementation of the Login Interface
	-->
<hibernate-mapping auto-import="true" default-lazy="false">


		<class name="org.spring.project.model.Registration" table="Login">
                <!--This code emphasize that usr_id is the primary key-->
		<id name="usr_id" column="usr_id">
		</id>
                <!--Other fields in the DB-->  
		<property name="usr_name" column="usr_name"/>
		<property name="usr_password" column="usr_password"/>
		</class>		
		</hibernate-mapping>
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:

Select allOpen in new window



So, what does this file do? Simply said, I have a table called Login which I want to map to POJO (or) Bean file Registration.java.

The name of the property refers to the bean variable, whereas the column refer to the table field.

3. Write the POJO class

Now we tell the spring that the Login table is mapped to Registration.java. But where is the Bean file? It's nothing but a simple POJO file with getters and setters for the table fields.

package org.spring.project.model;

public class Registration
{
       private String usr_id;
       private String usr_name;
       private String usr_password;
	   
	public String getUsr_id() {
		return usr_id;
	}
	public void setUsr_id(String usrId) {
		usr_id = usrId;
	}
	public String getUsr_name() {
		return usr_name;
	}
	public void setUsr_name(String usrName) {
		usr_name = usrName;
	}
	public String getUsr_password() {
		return usr_password;
	}
	public void setUsr_password(String usrPassword) {
		usr_password = usrPassword;
	}
}
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:

Select allOpen in new window




4. Call the Session Factory to access DB using Hibernate

In Spring, every major processing has to be implemented in the Service Implementation.
At this point, we need to wire up our session Factory with the Service Implementation to play with the DB, that can also be achieved without writing any ugly SQL queries.

package org.spring.project.service;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Expression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.spring.project.model.Registration;

@Service(“loginservice”)
@Transactional
public class ILoginImpl implements ILogin {

	@Autowired
	private SessionFactory sessionFactory;
	
	private final Logger log = Logger.getLogger(ILoginImpl.class);

	@Override
	public void insertData(Registration reg) {
		log.info("Inside implementation");
		sessionFactory.getCurrentSession().save(reg);

	}
}
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:

Select allOpen in new window



The class is annotated with @Service(“loginservice”).  This is the meta data that Spring will use when autowiring the userService property in the Controller created in the previous step.  We’ve explicitly defined the name “loginservice” in the annotation’s value, otherwise without it Spring would have named the bean “loginservice” automatically and the autowiring of this bean in the Controller and other classes would have failed.

@Transactional annotation will be recognized by the tx:annotation-driven element in the application context.  Having placed the annotation at the class level means that all methods in this class by default should adhere to these transaction rules.  

A Session Factory object gets autowired.  That class will deal with the actual ORM framework, in this case, Hibernate.

5. Controller to finish the course

Each and every request from JSP page will go to Controller and responses dispatched from Controller. Let's see a simple controller which gets the input and pass them to service, and return back the result to JSP Page.

package org.spring.project.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.tbingo.project.model.PGRequestModel;
import org.spring.project.service.ILogin;

@Controller
@RequestMapping("/login")
public class LoginController{	
	
	private final ILogin login;

	@Autowired
	public PGForwardController(ILogin login) {
		this.login = login;
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public String forwardPG(Registration reg,Model model){
                String message = "";
                if(login.insertData(reg))
                {success="Data inserted successfully";}
                else{success="Problem inserting Data";}
                model.addAttribute("message",success);//Pass the msg to a JSP page
		return "reg_success";//name of the JSP page
                // To display the msg in JSP page, use ${message}. Thats it		
	}
}
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:

Select allOpen in new window



Now you're set to go. Start the server, point your browser towards the login page and see how the data get inserted without writing even a single SQL query. Hibernate will do that for you.
If you want to see the query generated by SQL set the "show-sql' attribute as true in hibernate-configuration file.

If you have any queries, please feel free to contact me.
Asked On
2010-04-21 at 07:59:35ID2911
Tags

Spring

,

hibernate

,

spring hibernate integration

Topic

Web Frameworks

Views
2524

Comments

Add your Comment

Please Sign up or Log in to comment on this article.

Join Experts Exchange Today

Gain Access to all our Tech Resources

Get personalized answers

Ask unlimited questions

Access Proven Solutions

Search 3.2 million solutions

Read In-Depth How-To Guides

1000+ articles, demos, & tips

Watch Step by Step Tutorials

Learn direct from top tech pros

And Much More!

Your complete tech resource

See Plans and Pricing

30-day free trial. Register in 60 seconds.

Loading Advertisement...

Top Web Frameworks Experts

  1. Ray_Paseur

    43,268

    0 points yesterday

    Profile
    Rank: Savant
  2. smadeira

    11,000

    0 points yesterday

    Profile
    Rank: Wizard
  3. stephencolson

    6,000

    0 points yesterday

    Profile
    Rank: Master
  4. ChrisStanyon

    5,000

    0 points yesterday

    Profile
    Rank: Sage
  5. DaveBaldwin

    4,600

    0 points yesterday

    Profile
    Rank: Genius
  6. tbsgadi

    4,300

    0 points yesterday

    Profile
    Rank: Genius
  7. rowby

    4,000

    0 points yesterday

    Profile
    Rank: Master
  8. frisoft

    4,000

    0 points yesterday

    Profile
  9. maeltar

    4,000

    0 points yesterday

    Profile
    Rank: Guru
  10. Arrow_1

    3,800

    0 points yesterday

    Profile
    Rank: Master
  11. Slick812

    3,200

    0 points yesterday

    Profile
    Rank: Sage
  12. bportlock

    3,200

    0 points yesterday

    Profile
    Rank: Genius
  13. TheLearnedOne

    2,800

    0 points yesterday

    Profile
    Rank: Savant
  14. mplungjan

    2,800

    0 points yesterday

    Profile
    Rank: Savant
  15. pepr

    2,800

    0 points yesterday

    Profile
    Rank: Genius
  16. harperse

    2,800

    0 points yesterday

    Profile
    Rank: Guru
  17. ingwa

    2,800

    0 points yesterday

    Profile
    Rank: Sage
  18. tagit

    2,800

    0 points yesterday

    Profile
    Rank: Genius
  19. johanntagle

    2,800

    0 points yesterday

    Profile
    Rank: Sage
  20. Derokorian

    2,800

    0 points yesterday

    Profile
    Rank: Guru
  21. webmatrixpune

    2,600

    0 points yesterday

    Profile
    Rank: Guru
  22. bigeven2002

    2,300

    0 points yesterday

    Profile
    Rank: Guru
  23. arnold

    2,000

    0 points yesterday

    Profile
    Rank: Genius
  24. xterm

    2,000

    0 points yesterday

    Profile
    Rank: Sage
  25. Masteraco

    2,000

    0 points yesterday

    Profile
    Rank: Wizard

Hall Of Fame