In this tutorial, we are going to show a simple Spring Boot with Hibernate Example. The Spring Boot Hibernate integration is a crazy combination since Hibernate has its own importance.

Spring Boot Hibernate Integration :

Technologies:

  • Spring Boot 1.2.3.RELEASE
  • Java 1.7
  • Hibernate 4.3
  • Maven
  • MySql

Spring Boot Hibernate Project Structure :

A typical Maven project structure.

Spring Boot Hibernate

Project Dependencies:

pom.xml

Here the main important thing is to place the spring-boot-starter-data-jpa dependency; it will take all the internal dependencies.

Recommended: Spring Boot with JPA Integration

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 
    <groupId>org.springframework.samples</groupId> 
    <artifactId>SpringBoot_Hibernate_Example</artifactId> 
    <version>0.0.1-SNAPSHOT</version> 
    <properties> <!-- Generic properties --> 
        <java.version>1.7</java.version> 
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 
    </properties> 
    <parent> 
        <groupId>org.springframework.boot</groupId> 
        <artifactId>spring-boot-starter-parent</artifactId> 
        <version>1.2.3.RELEASE</version> 
        <relativePath /> 
    </parent> 
    <dependencies> 
        <dependency> 
            <groupId>org.springframework.boot</groupId> 
            <artifactId>spring-boot-starter-web</artifactId> 
        </dependency> 
        <dependency> 
            <groupId>org.springframework.boot</groupId> 
            <artifactId>spring-boot-starter-data-jpa</artifactId> 
        </dependency> 
        <dependency> 
            <groupId>mysql</groupId> 
            <artifactId>mysql-connector-java</artifactId> 
        </dependency> 
    </dependencies> 
    <build> 
        <plugins> 
            <plugin> 
                <groupId>org.springframework.boot</groupId> 
                <artifactId>spring-boot-maven-plugin</artifactId> 
            </plugin> 
        </plugins> 
    </build> 
</project>

Database Schema :

Create a person table in your database, since we are going to access this from our application ( Spring Boot Hibernate integration).

Database Table
CREATE TABLE person (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
pcity VARCHAR(255) NULL DEFAULT NULL,
name VARCHAR(255) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)

Create an Entity Class for person table.

Person.java
package com.onlinetutorialspoint.model;

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

@Entity
@Table(name = "person")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @Column(name = "pcity")
    private String city;

    public Person() {
        super();
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "Person [pid=" + id + ", pName=" + name + ", pCity=" + city
                + "]";
    }

}

There is no special in Peron.java class as part of Spring Boot Hibernate. It is as simple as a simple hibernate application entity file.

Configuration Properties :

Configuration information to get a connection from the database, and it is also consists of hibernate configurations like hibernate hbm2ddl auto.

Properties File :

application.properties
# Database
db.driver: com.mysql.jdbc.Driver
db.url: jdbc:mysql://localhost:3306/onlinetutorialspoint
db.username: root
db.password: 12345

# Hibernate
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql: true
hibernate.hbm2ddl.auto: create
entitymanager.packagesToScan: com

Create a DBConfiguration:

As part of the Spring Boot Hibernate integration, this is the main configuration file which is used to create a data source, Hibernate session Factory and managing transactions.

DBConfiguration.java

package com.onlinetutorialspoint.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class DBConfiguration {
    @Value("${db.driver}")
    private String DRIVER;

    @Value("${db.password}")
    private String PASSWORD;

    @Value("${db.url}")
    private String URL;

    @Value("${db.username}")
    private String USERNAME;

    @Value("${hibernate.dialect}")
    private String DIALECT;

    @Value("${hibernate.show_sql}")
    private String SHOW_SQL;

    @Value("${hibernate.hbm2ddl.auto}")
    private String HBM2DDL_AUTO;

    @Value("${entitymanager.packagesToScan}")
    private String PACKAGES_TO_SCAN;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(DRIVER);
        dataSource.setUrl(URL);
        dataSource.setUsername(USERNAME);
        dataSource.setPassword(PASSWORD);
        return dataSource;
    }

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(PACKAGES_TO_SCAN);
        Properties hibernateProperties = new Properties();
        hibernateProperties.put("hibernate.dialect", DIALECT);
        hibernateProperties.put("hibernate.show_sql", SHOW_SQL);
        hibernateProperties.put("hibernate.hbm2ddl.auto", HBM2DDL_AUTO);
        sessionFactory.setHibernateProperties(hibernateProperties);

        return sessionFactory;
    }

    @Bean
    public HibernateTransactionManager transactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory().getObject());
        return transactionManager;
    }
}

The DBConfiguration.java is a configuration file. Which will be executed by the Spring boot while it’s loading..

@Configuration annotation allows you to define configurations. you can get more about @Configuration and @Bean here.

@EnableTransactionManagement it enables the annotation-driven transaction management capability; we can also allow the transaction by using the <tx:*> XML namespace.

@Value is an annotation given by spring framework. It comes with Spring 3.0 release. @Value annotation is used for expression-driven dependency injection. A typical use case is to assign default field values using “${db.driver}” style expressions.

Create a DAO Class:

A PersonDAO.java class it performs basic crud operations. To make the Spring Boot Hibernate Example as simple as possible, I have created the method to get all persons from the database here.

PersonDAO.java

package com.onlinetutorialspoint.dao;

import java.util.List;

import javax.transaction.Transactional;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.onlinetutorialspoint.model.Person;

@Repository
@Transactional
public class PersonDAO {
    @Autowired
    private SessionFactory sessionFactory;

    private Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    public String savePerson(Person person) {
        Long isSuccess = (Long)getSession().save(person);
        if(isSuccess >= 1){
            return "Success";
        }else{
            return "Error while Saving Person";
        }
        
    }

    public boolean delete(Person person) {
        getSession().delete(person);
        return true;
    }

    @SuppressWarnings("unchecked")
    public List getAllPersons() {
        return getSession().createQuery("from Person").list();
    }
}

Create a Spring Controller :

PersonController.java

package com.onlinetutorialspoint.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.onlinetutorialspoint.dao.PersonDAO;
import com.onlinetutorialspoint.model.Person;

@Controller
@RequestMapping(value = "/person")
public class PersonController {
    @Autowired
    private PersonDAO personDao;

    @RequestMapping(value = "/delete")
    @ResponseBody
    public String delete(long id) {
        try {
            Person person = new Person();
            person.setId(id);
            personDao.delete(person);
        } catch (Exception ex) {
            return ex.getMessage();
        }
        return "Person succesfully deleted!";
    }

    @RequestMapping(value = "/save")
    @ResponseBody
    public String create(String name, String city) {
        try {
            Person person = new Person();
            person.setName(name);
            person.setCity(city);
            personDao.savePerson(person);
        } catch (Exception ex) {
            return ex.getMessage();
        }
        return "Person succesfully saved!";
    }
    @RequestMapping(value = "/allPersons")
    @ResponseBody
    public List getAllPersons() {
        try {
            return personDao.getAllPersons();
        } catch (Exception ex) {
            return null;
        }
    }
}

Create a Spring Boot Application Class :

Application.java

package com.onlinetutorialspoint;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

}

Well! We have done with Spring Boot Hibernate example. We need to run Aplication.java class now.  If everything went well, you could see the output log like below.

Spring Boot Hibernate Output

Now we can access the application by http://localhost:8080/person/

Insert the Person :

http://localhost:8080/person/save?name=chandra shekhar Goka&city=Hiderabad

Spring Boot Hibernate Save

Show All Persons :

http://localhost:8080/person/allPersons

Spring Boot Hibernate all

Delete a Person By Id :

http://localhost:8080/person/delete?id=1

Spring Boot Hibernate Delete

Happy Learning 🙂

Download Example