Home » Enterprise Java » Spring Hibernate Integration Example

About Santosh Balgar

Avatar photo
He is a Software Engineer working in an industry-leading organization. He has completed his bachelors from Visweswaraya Technological University. In his career, he has worked in designing and implementing various software systems involving Java/J2EE, Spring/ Spring Boot, React JS, JQuery, Hibernate and related database technologies. He loves to share his knowledge and always look forward to learning and explore new technologies. He loves to spend his free time with his family. He enjoys traveling and loves to play cricket.

Spring Hibernate Integration Example

In this post, we feature an example of Spring and Hibernate Integration.

Undoubtedly Spring and Hibernate are the most popular frameworks in the Java enterprise development world. Spring is a highly modular and lightweight framework offer integration with several other frameworks. Hibernate is one among them. Hibernate is the most popular Object-relational Mapping framework which has made database related operations very easy.

Spring Hibernate

In this article, we are going to study how to integrate both of these frameworks. Before that, I would suggest you read some articles to understand both of these frameworks. Some suggestions are listed below:



1. Introduction

Both Spring and Hibernate support annotation-based and XML based configuration. We are going to see how we can integrate both of these frameworks using Java-based configuration. For this example, I am using Java 8 and IntelliJ Idea as the development IDE.

2. Demo

In this tutorial, I am using Java’s inbuilt H2 database. We need to add below dependencies in pom.xml



This demo application offers a controller to fetch students from the H2 database. The controller is annotated with standard Spring annotation @RestController and offers an endpoint “/api/students”. Hibernate entity classes and repository classes are respectively using the appropriate annotations.

Below is the controller class,SimpleController

public class SimpleController {
    StudentService studentService;

    @RequestMapping(value = "/students", method = RequestMethod.GET)
    public @ResponseBody
    StudentResponse getStudents() throws Exception {
        StudentResponse response = new StudentResponse();
        return response;

In this demo exercise, I am using Hibernate’s criteria API to fetch the students from the database. Below is the sample,StudentDao

public class StudentDao {

    private SessionFactory sessionFactory;

    public List getAllStudents() throws Exception{
        Session session = sessionFactory.getCurrentSession();
        CriteriaQuery query = session.getCriteriaBuilder().createQuery(Student.class);
        return session.createQuery(query).getResultList();

    public void saveStudent(Student student) {
        Session session = sessionFactory.getCurrentSession();

Instead of XML based configuration, I am using Java-based configuration. Hibernate configuration is defined in the below class,HibernateConfiguration

public class HibernateConfiguration {
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();

        return sessionFactory;

    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();

        return dataSource;

    public PlatformTransactionManager hibernateTransactionManager() {
        HibernateTransactionManager transactionManager
                = new HibernateTransactionManager();
        return transactionManager;

    private final Properties hibernateProperties() {
        Properties hibernateProperties = new Properties();
                "hibernate.hbm2ddl.auto", "create-drop");
                "hibernate.dialect", "org.hibernate.dialect.H2Dialect");

        return hibernateProperties;

Along with Hibernate Configuration, we need to add configuration class to load different beans and an application initializer class to load our application.WebConfig

public class WebConfig {
    public StudentService studentService() {
        return new StudentService();

    public StudentDao studentDao() {
        return new StudentDao();

This class enables the annotation-based component scan and provides bean definition.ApplicationInitialize

public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    protected Class[] getRootConfigClasses() {
        return new Class[] {

    protected Class[] getServletConfigClasses() {
        return null;

    protected String[] getServletMappings() {
        return new String[] {

This is like web.xml which defines the default path and root configuration of our application.

This is a classic Spring application, hence to run we have to build a deployable war file and manually deploy in the Tomcat server. For this to happen, add a build configuration in pom.xml as below,


Package the solution into the war file. A packaged war file can be found under the target folder of your project.

Download the Tomcat web server and place the war file under <tomcat home directory>/webapps.

Go to command prompt and navigate to <tomcat home directory>/bin and run statup.bat

Once Tomcat is successfully started, access http://localhost:8080/api/students to see student details as a JSON.

Output: When you access the API /api/students offered by the demo application, you will receive an output similar to below,


3. Download the Source Code

You can download the full source code of this example here: Spring Hibernate Integration Example

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments