You are on page 1of 16

Spring Examples with Hibernate : Chapter 37

Posted by Dinesh Rajput


In this chapter we will see that how to configure the Hibernate with Spring
framework.
Hibernate is a powerful technology for persisting data in any kind of Application.
Spring, on the other hand is a dependency injection framework that supports
IOC. The beauty of Spring is that it can integrates well with most of the prevailing
popular technologies.
If you are new to Spring and Hibernate frameworks, please read the introduction
articles on Spring and Hibernate before start reading this article. DineshonJava
has explained in Introduction to Spring Framework. This article will help you to
understand the fundamentals of the Spring framework. In another article
Introduction to Hibernate published on 27/03/2012 by DineshonJava explains
what is ORM framework and how to start writing the simple hibernate
application.

Spring and Hibernate:


As a pre-requisite, let us understand the need for such integration before we
actually get into the integration between these two technologies. It is well known
that Hibernate is a powerful ORM tool that lies between Application and
Database. It enables Application to access data from any database in a platformindependent manner. There is no need for the Application to depend on the lowlevel JDBC details like managing connection, dealing with statements and result
sets. All the necessary details for accessing a particular data source is easily
configurable in Xml files. Another good thing is that Hibernate can be coupled well
with both J2SE and J2EE Applications.
One of the problem with using Hibernate is that the client Application that
accesses the database using Hibernate Framework has to depend on the
Hibernate APIs like Configuration, SessionFactory and Session. These objects will
continue to get scattered across the code throughout the Application. Moreover, the
Application code has to manually maintain and manage these objects. In the case of
Spring, the business objects can be highly configurable with the help of IOC
Container. In simple words, the state of an object can be externalized from the
Application code. It means that now it is possible to use the Hibernate objects as
Spring Beans and they can enjoy all the facilities that Spring provides.

Integration Spring and Hibernate:

We can simply integrate


Hibernate configuration with the Spring than struts 2 , In hibernate framework file
hibernate.cfg.xml using for the hibernate configuration with the application but in
case of Spring there are no need to use this file we can simply configure with in the

Spring.xml or applicationContext.xml configuration file. The following sections


cover the various steps involved in the Spring-Hiberante integration along with a
detailed explanation.
Using Hibernate Mapping file with Spring
1. Creating Database and Table(Employee Table)
2. Creating Employee Class(Employee.java)
3. Creating the Hibernate Mapping file for Employee table(Employee.hbm.xml)
4. Creating the Spring Configuration File (spring.xml)
5. Creating the DAO class (EmployeeDao.java)
6. Creating Application Class for using this
We can also use the Annotation for using this example with following
steps.
1. Creating Database and Table(Employee Table)
2. Creating Employee Class with using @Entity annotation(Employee.java)
3. Creating the Spring Configuration File (spring.xml) but creating bean with
using annotation
4. Creating the DAO class (EmployeeDao.java)
5. Creating Application Class for using this
-->
Now first we see that example using annotation.

Step 1. Creating Database and Table(Employee Table)


view plainprint?
1. CREATE TABLE Employee(
2.

EMPID INT NOT NULL AUTO_INCREMENT,

3.

NAME VARCHAR(20) NOT NULL,

4.

AGE INT NOT NULL,

5.

SALARY BIGINT NOT NULL,

6.

PRIMARY KEY (ID)

7. );
Step 2: Creating Employee Class
Employee.java
view plainprint?
1. package com.dineshonjava.sdnext.domain;
2.
3. import javax.persistence.Column;

4. import javax.persistence.Entity;
5. import javax.persistence.GeneratedValue;
6. import javax.persistence.GenerationType;
7. import javax.persistence.Id;
8. import javax.persistence.Table;
9.
10./**
11. * @author Dinesh Rajput
12. *
13. */
14.@Entity
15.@Table(name="Employee")
16.public class Employee {
17. @Id
18. @Column(name="EMPID")
19. @GeneratedValue(strategy=GenerationType.AUTO)
20. private int empid;
21.
22. @Column(name="NAME")
23. private String name;
24.
25. @Column(name="AGE")
26. private int age;
27.

28. @Column(name="SALARY")
29. private long salary;
30. /**
31. * @return the empid
32. */
33. public int getEmpid() {
34. return empid;
35. }
36. /**
37. * @param empid the empid to set
38. */
39. public void setEmpid(int empid) {
40. this.empid = empid;
41. }
42. /**
43. * @return the name
44. */
45. public String getName() {
46. return name;
47. }
48. /**
49. * @param name the name to set
50. */
51. public void setName(String name) {

52. this.name = name;


53. }
54. /**
55. * @return the age
56. */
57. public int getAge() {
58. return age;
59. }
60. /**
61. * @param age the age to set
62. */
63. public void setAge(int age) {
64. this.age = age;
65. }
66. /**
67. * @return the salary
68. */
69. public long getSalary() {
70. return salary;
71. }
72. /**
73. * @param salary the salary to set
74. */
75. public void setSalary(long salary) {

76. this.salary = salary;


77. }
78.
79. public String toString(){
80. return "EMPLOYEE{empid- "+this.empid+" name- "+this.name+
81.

" age- "+this.age+" salary- "+this.salary+"}";

82. }
83.}
Step 3: Creating the Spring Configuration File (spring.xml)
view plainprint?
1. <beans xmlns:aop="http://www.springframework.org/schema/aop" xmlns:con
text="http://www.springframework.org/schema/context" xmlns:p="http://ww
w.springframework.org/schema/p" xmlns:security="http://www.springframew
ork.org/schema/security" xmlns:tx="http://www.springframework.org/schema
/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmln
s="http://www.springframework.org/schema/beans" xsi:schemalocation="htt
p://www.springframework.org/schema/beans http://www.springframework.org/
schema/beans/spring-beans-2.5.xsd
2.

http://www.springframework.org/schema/context http://www.springframe
work.org/schema/context/spring-context-2.5.xsd

3.

http://www.springframework.org/schema/security http://www.springframe
work.org/schema/security/spring-security-2.0.4.xsd

4.

http://www.springframework.org/schema/aop http://www.springframewor
k.org/schema/aop/spring-aop-2.5.xsd

5.

http://www.springframework.org/schema/tx http://www.springframework.org/
schema/tx/spring-tx-2.5.xsd">

6.
7. <context:annotation-config></context:annotation-config>
8.
9. <context:component-scan basepackage="com.dineshonjava.sdnext.dao.impl">

10.</context:component-scan>
11.
12.<!-- Creating data source -->
13.<bean class="org.apache.commons.dbcp.BasicDataSource" id="dataSource"
>
14. <property name="driverClassName" value="com.mysql.jdbc.Driver"></prop
erty>
15. <property name="url" value="jdbc:mysql://localhost:3306/DAVDB"></prope
rty>
16. <property name="username" value="root"></property>
17. <property name="password" value="root"></property>
18. <property name="initialSize" value="2"></property>
19. <property name="maxActive" value="5"></property>
20.</bean>
21.
22.<!-- Creating session factory -->
23.<bean class="org.springframework.orm.hibernate3.annotation.AnnotationSes
sionFactoryBean" id="sessionFactory">
24.

<property name="dataSource" ref="dataSource"></property>

25.

<property name="hibernateProperties">

26.
27.
28.

<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect

29.

</prop>

30.

<prop key="hibernate.show_sql">true</prop>

31.

</props>

32.

</property>

33.
34.

<property name="annotatedClasses">

35.

<list>

36. <value>
37.

com.dineshonjava.sdnext.domain.Employee

38.

</value>

39.
40.

</list>
</property>

41.</bean>
42.
43.<bean class="com.dineshonjava.sdnext.dao.impl.EmployeeDaoImpl" id="em
ployeeDaoImpl">
44.

<property name="sessionFactory" ref="sessionFactory">

45.</property></bean>
46.</beans>
Step 4: Creating the DAO class (EmployeeDao.java)
view plainprint?
1. package com.dineshonjava.sdnext.dao;
2.
3. import java.util.List;
4.
5. import com.dineshonjava.sdnext.domain.Employee;
6.
7. /**

8.

* @author Dinesh Rajput

9.

10. */
11.public interface EmployeeDao {
12. /**
13. * This is the method to be used to create
14. * a record in the Employee table.
15. */
16. void createEmployee(Employee employee);
17. /**
18. * This is the method to be used to list down
19. * a record from the Employee table corresponding
20. * to a passed Employee id.
21. */
22. Employee getEmployee(Integer empid);
23. /**
24. * This is the method to be used to list down
25. * all the records from the Employee table.
26. */
27. List<employee> listEmployees();
28. /**
29. * This is the method to be used to delete
30. * a record from the Employee table corresponding
31. * to a passed Employee id.

32. */
33. void delete(Employee employee);
34. /**
35. * This is the method to be used to update
36. * a record into the Employee table.
37. */
38. void update(Employee employee);
39.}
40.</employee>
SuperHibernateDaoSupport.java
view plainprint?
1. package com.dineshonjava.sdnext.dao.util;
2.
3. import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
4.
5. /**
6.

* @author Dinesh Rajput

7.

8.

*/

9. public abstract class SuperHibernateDaoSupport extends HibernateDaoSuppo


rt {
10.
11.}
EmployeeDaoImpl.java
view plainprint?

1. package com.dineshonjava.sdnext.dao.impl;
2.
3. import java.util.List;
4.
5. import org.springframework.stereotype.Repository;
6.
7. import com.dineshonjava.sdnext.dao.EmployeeDao;
8. import com.dineshonjava.sdnext.dao.util.SuperHibernateDaoSupport;
9. import com.dineshonjava.sdnext.domain.Employee;
10.
11./**
12. * @author Dinesh Rajput
13. *
14. */
15.@Repository
16.public class EmployeeDaoImpl extends SuperHibernateDaoSupport implemen
ts EmployeeDao {
17.
18. @Override
19. public void createEmployee(Employee employee) {
20. getHibernateTemplate().saveOrUpdate(employee);
21. }
22.
23. @Override
24. public Employee getEmployee(Integer empid) {

25. return (Employee) getHibernateTemplate().get(Employee.class, empid);


26. }
27.
28. @Override
29. public List<employee> listEmployees() {
30. return getHibernateTemplate().find("FROM EMPLOYEE");
31. }
32.
33. @Override
34. public void delete(Employee employee) {
35. getHibernateTemplate().delete(employee);
36. }
37.
38. @Override
39. public void update(Employee employee) {
40. getHibernateTemplate().saveOrUpdate(employee);
41. }
42.}
43.</employee>
Step 5: Creating Application Class for using this
view plainprint?
1. package com.dineshonjava.sdnext.main;
2.
3. import org.springframework.context.ApplicationContext;

4. import org.springframework.context.support.ClassPathXmlApplicationContext;
5.
6. import com.dineshonjava.sdnext.dao.EmployeeDao;
7. import com.dineshonjava.sdnext.domain.Employee;
8.
9. /**
10. * @author Dinesh Rajput
11. *
12. */
13.public class EmpMainApp {
14.
15. /**
16. * @param args
17. */
18. public static void main(String[] args) {
19.
20.ApplicationContext context = new ClassPathXmlApplicationContext("spring.x
ml");
21.EmployeeDao empDao = (EmployeeDao) context.getBean("employeeDaoImpl
");
22.
23. Employee employee = new Employee();
24. employee.setName("Dinesh");
25. employee.setAge(25);
26. employee.setSalary(50000l);

27. System.out.println("------Records Creation--------" );


28. empDao.createEmployee(employee);
29. System.out.println("------Listing Multiple Records--------" );
30. List<employee> employees = empDao.listEmployees();
31. for (Employee emp: employees) {
32.
33.

System.out.print(emp);
}

34. System.out.println("------find one Records--------" );


35. Employee employee = empDao.getEmployee(3);
36. System.out.print(employee);
37. System.out.println("------Delete one Records--------" );
38. empDao.delete(employee);
39. }
40.}
41.</employee>
Output:
log4j:WARN No appenders could be found for logger
(org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
------Records Creation-------Hibernate: insert into Employee (AGE, NAME, SALARY) values (?, ?, ?)
------Listing Multiple Records-------Hibernate: select employee0_.EMPID as EMPID0_, employee0_.AGE as AGE0_,
employee0_.NAME as NAME0_, employee0_.SALARY as SALARY0_ from Employee
employee0_
EMPLOYEE{empid- 1 name- Dinesh age- 25 salary- 50000}EMPLOYEE{empid- 2
name- Anamika age- 20 salary- 30000}EMPLOYEE{empid- 3 name- Nimmo age- 24
salary- 30020}EMPLOYEE{empid- 4 name- Adesh age- 24 salary30011}EMPLOYEE{empid- 5 name- Vinesh age- 22 salary20011}EMPLOYEE{empid- 6 name- Rajesh age- 25 salary50000}EMPLOYEE{empid- 7 name- DAV age- 21 salary- 50000}

------find one Records-------Hibernate: select employee0_.EMPID as EMPID0_0_, employee0_.AGE as AGE0_0_,


employee0_.NAME as NAME0_0_, employee0_.SALARY as SALARY0_0_ from
Employee employee0_ where employee0_.EMPID=?
EMPLOYEE{empid- 3 name- Nimmo age- 24 salary- 30020}
------Delete one Records-------Hibernate: delete from Employee where EMPID=?

You might also like