Java ProgrammingLearn How to Connect Spring ORM with Hibernate

Learn How to Connect Spring ORM with Hibernate

Connect Spring ORM

Spring ORM integration with Hibernate can be an important milestone to building a quality enterprise application. Spring is one of the most popular enterprise application development frameworks and Hibernate is one of the most popular database to object mapping frameworks. However, since there are multiple versions of both Spring and Hibernate, you need to note that there might be compatibility issues between both frameworks depending on several factors. For example, incompatibility issues could be the result of Hibernate classes moving between classes. There is no definitive guide on matching compatible versions, compatibility depends on several known and unknown factors. You need to find compatible versions. Compatibility issues should not discourage you from undertaking what is a rewarding initiative. Spring and Hibernate integration needs to follow a certain process or a series of steps to be successful. This article describes the standard steps and principles of integrating Spring ORM with Hibernate and provides an example.

Integration principles
You need to keep in mind the following broad principles.
• You need to first find out compatible versions of Spring and Hibernate. Multiple versions are available but due to various reasons, not all versions of both frameworks may be compatible. To start, the versions need to be compatible.
• Identify the dependencies carefully and specify ways your project is going to fulfil those dependencies. Also identify possible resolutions in cases the dependencies face an issue or a problem. Note that dependency-related issues are real and expected.
• While every component in your project structure is important in its own right, you need to be especially careful in configuring the DAO classes because these classes will be constituting the interface to the database and persistent data. You can say the classes constitute the core of the integration project.

Integration steps
The objective is to provide the broad steps to integrate Spring ORM and Hibernate.

Configure the database
Identify the right database and set up the tables with the help of scripts.

Configure the project structure
The project should comprise everything you need to integrate Spring ORM and Hibernate. It will define how the various elements such as XML and SQL files. The image below shows an imaginary project structure which will be used for the integration.

State the dependencies
You need to state or define the dependencies on a project management tool such as Maven. The main dependencies are going to be the following:
• Depending on the version of Spring you are using, declare the spring-tx and spring-context for the core Spring functionalities.
• Spring ORM dependency to get Spring ORM support. This is one of the most important dependencies for integrating Spring and Hibernate.
• The Hibernate framework is dependent on the hibernate-entitymanager and hibernate-core.
• For database connection, state the dependency on the mysql-connector-java for MySQL driver.

Deciding between Model Class and Entity Bean
This decision will depend on your project considerations and requirements. Just to give a perspective to help your decision, a model object is a type of object that contains application data, provides access to the data and helps manipulate the data. A model class comprises one or more model objects. An entity bean, on the other hand, is a remote object that manages persistent data and performs manipulation on the data. It uses many dependent Java objects and is identified by a Primary Key.

Configuring Data Access Object (DAO) classes
You will need to decide the number of DAO classes you will have in the project, their role in the project, the methods you will add to the classes and their interaction with other entities that are attempting to access the database or persistent data through the DAO classes.

Configuring Spring Beans for Hibernate Integration
Now you are approaching the main objective of the project – integration between Spring and Hibernate. To configure, you need to provide database connection details to Hibernate. You can do it by providing all details in hibernate Properties or by creating a datasource and passing it to Hibernate. Depending on how Spring and Hibernate are mapped, Spring ORM provides two classes:
• org.springframework.orm.hibernate3.LocalSessionFactoryBean for XML-based mapping.
• org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean for annotations-based mapping.

Implementation
Let’s take an example to show the details. We will have the following components to make the application ready.
First one is an entity class; here it is Student entity containing student attributes. The class is described below

Listing 1: – Student entity class

package com.eduonix.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

//Created for Eduonix
@Entity
@Table(name="STUDENT")
public class StudentEntity {

    @Id
    @Column(name="ID")
    @GeneratedValue
    private Integer id;

    @Column(name="FIRSTNAME")
    private String firstname;

    @Column(name="LASTNAME")
    private String lastname;

    @Column(name="EMAIL")
    private String email;

    //Setters and Getters
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFirstname() {
        return firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
}

Now the next class is the Student DAO interface containing two methods for adding students and displaying them whenever is requested.

Listing 2: – Student DAO class

package com.eduonix.dao;

import java.util.List;
import com.eduonix.entity.StudentEntity;

//Created for Eduonix
public interface StudentDAO
{
    public void addStudent(StudentEntity student);
    public List<StudentEntity> getAllStudents();

}

Following is the DAO implementation class implementing the methods defined in the DAO interface.

Listing 3: – DAO implementation class

package com.eduonix.dao;

import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.eduonix.entity.StudentEntity;
//Created for Eduonix
@Repository
public class StudentDaoImpl implements StudentDAO  {
	@Autowired
    private SessionFactory sessionFactory;
	@Override
	public void addStudent(StudentEntity student) {
		this.sessionFactory.getCurrentSession().save(student);
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<StudentEntity> getAllStudents() {
		return this.sessionFactory.getCurrentSession().createQuery("from StudentEntity").list();
	}

}

This is the manager interface. It takes the request from the controller and does the routing to the DAO implementation class.

Listing 4: – Student manager class

package com.eduonix.service;

import java.util.List;
import com.eduonix.entity.StudentEntity;

//Created for Eduonix
public interface StudentManager {
	public void addStudent(StudentEntity student);
    public List<StudentEntity> getAllStudents();

}

This is the manager implementation of the above methods.

Listing 5: – Student manager implementation class

package com.eduonix.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.eduonix.dao.StudentDAO;
import com.eduonix.entity.StudentEntity;

//Created for Eduonix
@Service
public class StudentManagerImpl implements StudentManager {

	@Autowired
    private StudentDAO studentDAO;

	@Override
	@Transactional
	public void addStudent(StudentEntity student) {
		studentDAO.addStudent(student);
	}

	@Override
	@Transactional
	public List<StudentEntity> getAllStudents() {
		return studentDAO.getAllStudents();
	}

	public void setStudentDAO(StudentDAO studentDAO) {
		this.studentDAO = studentDAO;
	}
}

Now, this is the controller class to control all the requests.

Listing 6: – Student controller class

package com.eduonix.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.eduonix.entity.StudentEntity;
import com.eduonix.service.StudentManager;

//Created for Eduonix

@Controller
public class StudentController {

	@Autowired
	private StudentManager studentManager;

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String listStudents(ModelMap map)
	{
		map.addAttribute("student", new StudentEntity());
		map.addAttribute("studentList", studentManager.getAllStudents());

		return "StudentList";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String addStudent(@ModelAttribute(value="student") StudentEntity student, BindingResult result)
	{
		studentManager.addStudent(student);
		return "redirect:/";
	}

	public void setStudentManager(StudentManager studentManager) {
		this.studentManager = studentManager;
	}
}

This is the hibernate configuration file, to do the mapping

Listing 7: – Hibernate configuration class

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Created for eduonix --> 
<hibernate-configuration>
    <session-factory>
        <mapping class="com.eduonix.entity.StudentEntity" />
    </session-factory>
</hibernate-configuration>

Now, if the application is run, then it will have the capabilities to add students and then display the list wherever requested from any web application.

Conclusion: –
You need to note that the above steps are broad steps and in real-life integration scenarios, there can be variances considering the scenarios. Still, the broad principles and steps will remain the same. For example, you can choose XML-based or annotation-based mapping between the Spring and Hibernate or you can use one of the many ways available to connect the database with Hibernate. However, you need to note that the variances in project implementation can be mostly related to the differences arising because of the differences in implementation in case of different versions of Spring and Hibernate.

1 COMMENT

  1. Hi,
    It was a nice tutorial until the end of it which you did not put your spring configuration file.
    please put also your spring configuration file.

    Thanks.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -