Spring Boot Hibernate Example | Spring Boot Hibernate Integration | Boot CRUD Hibernate

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
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.
Technologies:
Spring Boot 1.2.3.RELEASE
Java 1.7
Hibernate 4.3
Maven
MySql
A typical Maven project structure.
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
<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).
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.
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 :
# 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.

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.

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 :

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 :

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.
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
Show All Persons :
http://localhost:8080/person/allPersons
Delete a Person By Id :
http://localhost:8080/person/delete?id=1
Happy Learning 🙂


springboot_hibernate_example

Spring Boot Hibernate With CRUD Operations
File size: 22 MB
Downloads: 5269


Spring Boot JPA Integration Example
Spring Boot Security MySQL Database Integration Example
Spring Boot PDF iText integration with String Template
How to set Spring Boot SetTimeZone
Spring Boot How to change the Tomcat to Jetty Server
How to change Spring Boot Tomcat Port Number
Simple Spring Boot Example
How To Change Spring Boot Context Path
Spring Boot Actuator Database Health Check
Spring Boot Multiple Data Sources Example
Spring Boot MVC Example Tutorials
Spring Boot MockMvc JUnit Test Example
External Apache ActiveMQ Spring Boot Example
Spring Boot H2 Database + JDBC Template Example
Spring Boot Kafka Producer Example

Spring Boot JPA Integration Example
Spring Boot Security MySQL Database Integration Example
Spring Boot PDF iText integration with String Template
How to set Spring Boot SetTimeZone
Spring Boot How to change the Tomcat to Jetty Server
How to change Spring Boot Tomcat Port Number
Simple Spring Boot Example
How To Change Spring Boot Context Path
Spring Boot Actuator Database Health Check
Spring Boot Multiple Data Sources Example
Spring Boot MVC Example Tutorials
Spring Boot MockMvc JUnit Test Example
External Apache ActiveMQ Spring Boot Example
Spring Boot H2 Database + JDBC Template Example
Spring Boot Kafka Producer Example






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











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”: {}
},









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









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

download example is empty









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

Such a nice blog.
I have read an amazing article here.









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

session factory not getting inject.throwing null pointer exception









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 https://repo.maven.apache.org/maven2 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 (https://repo.maven.apache.org/maven2): Failed to connect to repo.maven.apache.org/
151.101.40.215:443 and ‘parent.relativePath’ points at no local POM










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






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




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





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”: {}
},




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”: {}
},





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




@Configuration is an annotation, you can get more about @Configuration and @Bean here..
Its a link, Please mkae it look like a link. 🙂





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

download example is empty




download example is empty





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

Such a nice blog.
I have read an amazing article here.




Such a nice blog.
I have read an amazing article here.





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

session factory not getting inject.throwing null pointer exception




session factory not getting inject.throwing null pointer exception





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 https://repo.maven.apache.org/maven2 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 (https://repo.maven.apache.org/maven2): Failed to connect to repo.maven.apache.org/
151.101.40.215:443 and ‘parent.relativePath’ points at no local POM




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 https://repo.maven.apache.org/maven2 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 (https://repo.maven.apache.org/maven2): Failed to connect to repo.maven.apache.org/
151.101.40.215:443 and ‘parent.relativePath’ points at no local POM
 


Δ
 Spring Boot – Hello World
 Spring Boot – MVC Example
 Spring Boot- Change Context Path
 Spring Boot – Change Tomcat Port Number
 Spring Boot – Change Tomcat to Jetty Server
 Spring Boot – Tomcat session timeout
 Spring Boot – Enable Random Port
 Spring Boot – Properties File
 Spring Boot – Beans Lazy Loading
 Spring Boot – Set Favicon image
 Spring Boot – Set Custom Banner
 Spring Boot – Set Application TimeZone
 Spring Boot – Send Mail
 Spring Boot – FileUpload Ajax
 Spring Boot – Actuator
 Spring Boot – Actuator Database Health Check
 Spring Boot – Swagger
 Spring Boot – Enable CORS
 Spring Boot – External Apache ActiveMQ Setup
 Spring Boot – Inmemory Apache ActiveMq
 Spring Boot – Scheduler Job
 Spring Boot – Exception Handling
 Spring Boot – Hibernate CRUD
 Spring Boot – JPA Integration CRUD
 Spring Boot – JPA DataRest CRUD
 Spring Boot – JdbcTemplate CRUD
 Spring Boot – Multiple Data Sources Config
 Spring Boot – JNDI Configuration
 Spring Boot – H2 Database CRUD
 Spring Boot – MongoDB CRUD
 Spring Boot – Redis Data CRUD
 Spring Boot – MVC Login Form Validation
 Spring Boot – Custom Error Pages
 Spring Boot – iText PDF
 Spring Boot – Enable SSL (HTTPs)
 Spring Boot – Basic Authentication
 Spring Boot – In Memory Basic Authentication
 Spring Boot – Security MySQL Database Integration
 Spring Boot – Redis Cache – Redis Server
 Spring Boot – Hazelcast Cache
 Spring Boot – EhCache
 Spring Boot – Kafka Producer
 Spring Boot – Kafka Consumer
 Spring Boot – Kafka JSON Message to Kafka Topic
 Spring Boot – RabbitMQ Publisher
 Spring Boot – RabbitMQ Consumer
 Spring Boot – SOAP Consumer
 Spring Boot – Soap WebServices
 Spring Boot – Batch Csv to Database
 Spring Boot – Eureka Server
 Spring Boot – MockMvc JUnit
 Spring Boot – Docker Deployment