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 :


  • 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:


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

<project xmlns="" xmlns:xsi="" xsi:schemaLocation=""> 
    <properties> <!-- Generic properties --> 
        <relativePath /> 

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 an Entity Class for person table.
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;

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

    public Person() {

    public Long getId() {
        return id;

    public void setId(Long id) { = id;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public String getCity() {
        return city;

    public void setCity(String city) { = city;

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


There is no special in 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 :
# 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 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.

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;

public class DBConfiguration {
    private String DRIVER;

    private String PASSWORD;

    private String URL;

    private String USERNAME;

    private String DIALECT;

    private String SHOW_SQL;

    private String HBM2DDL_AUTO;

    private String PACKAGES_TO_SCAN;

    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        return dataSource;

    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        Properties hibernateProperties = new Properties();
        hibernateProperties.put("hibernate.dialect", DIALECT);
        hibernateProperties.put("hibernate.show_sql", SHOW_SQL);
        hibernateProperties.put("", HBM2DDL_AUTO);

        return sessionFactory;

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

The 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 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.

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;

public class PersonDAO {
    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";
            return "Error while Saving Person";

    public boolean delete(Person person) {
        return true;

    public List getAllPersons() {
        return getSession().createQuery("from Person").list();

Create a Spring Controller :

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;

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

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

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

Create a Spring Boot Application Class :

package com.onlinetutorialspoint;

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

public class Application {
  public static void main(String[] args) {, args);


Well! We have done with Spring Boot Hibernate example. We need to run 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 :


Spring Boot Hibernate all

Delete a Person By Id :


Spring Boot Hibernate Delete

Happy Learning 🙂

Download Example


  1. prabhakar June 28, 2017 at 10:51 am - Reply

    Excellent article
    but i have one requirement how to get a single person details using id

    • Viswanath July 31, 2017 at 5:11 pm - Reply

      I believe using the Repository of Spring Data is more straightforward .. you need to write any persistence code, ie handling session, sessionfactory, datasource, etc.. it is very simple

  2. Neelam Panwar August 14, 2017 at 6:18 pm - Reply

    Hi Chandrashekhar,
    I am new to spring boot and I have followed exactly this configuration and getting following response.
    i just want me response to be list of json objects(present under entity tag in below response).
    how can i remove other unwanted stuff from this resoponse body.
    please suggest.
    “context”: {
    “headers”: {},
    “entity”: [
    “name”: “abe”,
    “age”: “23”
    “name”: “omy”,
    “age”: “42”,

    “entityType”: “java.util.ArrayList”,
    “entityAnnotations”: [],
    “entityStream”: {
    “committed”: false,
    “closed”: false
    “length”: -1,
    “language”: null,
    “location”: null,
    “date”: null,
    “lastModified”: null,
    “committed”: false,
    “allowedMethods”: [],
    “mediaType”: null,
    “acceptableMediaTypes”: [
    “type”: “*”,
    “subtype”: “*”,
    “parameters”: {},
    “quality”: 1000,
    “wildcardType”: true,
    “wildcardSubtype”: true
    “lengthLong”: -1,
    “links”: [],
    “entityTag”: null,
    “stringHeaders”: {},
    “entityClass”: “java.util.ArrayList”,
    “responseCookies”: {},
    “acceptableLanguages”: [
    “requestCookies”: {}

  3. Shailendra September 18, 2017 at 4:03 am - Reply

    @Configuration is an annotation, you can get more about @Configuration and @Bean here..

    Its a link, Please mkae it look like a link. 🙂

  4. Ramandeep Singh September 26, 2017 at 10:09 am - Reply

    download example is empty

  5. Melanie Glastrong November 9, 2017 at 8:01 am - Reply

    Such a nice blog.

    I have read an amazing article here.

  6. Guru December 12, 2018 at 3:25 pm - Reply

    session factory not getting inject.throwing null pointer exception

  7. Vishwa April 8, 2019 at 1:00 pm - Reply

    After importing project

    Project build error: Non-resolvable parent POM for org.springframework.samples:SpringBoot_Hibernate_Example:0.0.1-SNAPSHOT: Failure to transfer org.springframework.boot:spring-boot-starter-parent:pom:
    1.2.3.RELEASE from was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original
    error: Could not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom:1.2.3.RELEASE from/to central ( Failed to connect to and ‘parent.relativePath’ points at no local POM

Leave A Comment