Search Suggest

Spring Boot Hibernate Example

In this post, we are going to see how to create Spring boot hibernate example.

We will use Spring boot 1.5.3 Release version, it comes with hibernate 5. We will create a Spring boot hibernate application which will have JSP as user interface. It will provide user interface from which you can add, update or delete customer database.We will use controller, services and DAO classes to achieve these functionalities.We will connect to MySQL database using SessionFactory class of hibernate.

Github Source Code


Spring Boot Hibernate Example

Here are steps to create a Spring boot Hibernate example.

Project Structure

Tools used for creating below project:

  1. Spring Boot 1.5.3.RELEASE
  2. Spring 4.3.8.RELEASE
  3. Tomcat Embed 8
  4. Maven 3
  5. Java 8
  6. Eclipse
  7. Hibernate 5.3.5
  8. MySQL 5.7.18

Step 1:  Create a dynamic web project using maven in eclipse named “SpringBootHibernateExample”.
Step 2: Change “pom.xml” as below:

<project xmlns="" xmlns:xsi=""

<name>SpringBootHibernateExample Maven Webapp</name>
<!-- JSTL for JSP -->

<!-- For JSP compilation -->
<!-- -->

The spring-boot-starter-parent provides you all maven defaults required for any spring project.
Since we are developing a web application, we also need to add spring-boot-starter-web dependency and also we need to include pring-boot-starter-data-jpa to run this application with hibernate.You need to also put mysql-connector-java for MySql JDBC driver.If you are using any other database, you need to use different database connector.
Let’s do hibernate configuration first.

Hibernate Configuration

Step 3: Create a file named “” in package .org.arpit.java2blog

package org.arpit.java2blog; 
import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

public class HibernateConfiguration {
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;

Above class is annotated with @Configuration and @Bean annotation. These annotations are used to define bean in Spring.
@Configuration is analogous to <beans> tag in Spring XML configuration and @Bean is analogous to <bean> tag.
@Value annotation is used to inject variables from properties files. In this case, it will read from which we are going to create in next step.

Step 4: Create a file named “” in package /src/main/resources

spring.mvc.view.prefix: /WEB-INF/
spring.mvc.view.suffix: .jsp

# Database
db.driver: com.mysql.jdbc.Driver
db.url: jdbc:mysql://localhost:3306/CustomerData
db.username: root
db.password: admin

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

Model Class

Step 5: Create a file named “” in package .org.arpit.java2blog.model

package org.arpit.java2blog.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;

* This is our model class and it corresponds to Customer table in database
public class Customer{

int id;

String customerName;

String email;

public Customer() {
public Customer(String customerName,String email) {
public String getCustomerName() {
return customerName;
public void setCustomerName(String customerName) {
this.customerName = customerName;
public String getEmail() {
return email;
public void setEmail(String email) { = email;
public int getId() {
return id;
public void setId(int id) { = id;


@Entity is used for making a persistent pojo class.For this java class,you will have corresponding table in database. @Column is used to map annotated attribute to corresponding column in table.

Create Customer table:

Create customer table in database with following DDL.

`customerName` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,

Controller Class :

Step 6: Create a file named “” in package .org.arpit.java2blog.controller

package org.arpit.java2blog.controller;

import java.util.List;

import org.arpit.java2blog.model.Customer;
import org.arpit.java2blog.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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;

public class CustomerController {

CustomerService customerService;

@RequestMapping(value = "/getAllCustomers", method = RequestMethod.GET, headers = "Accept=application/json")
public String getAllCustomers(Model model) {

List<Customer> listOfCustomers = customerService.getAllCustomers();
model.addAttribute("customer", new Customer());
model.addAttribute("listOfCustomers", listOfCustomers);
return "customerDetails";

@RequestMapping(value = "/", method = RequestMethod.GET, headers = "Accept=application/json")
public String goToHomePage() {
return "redirect:/getAllCustomers";

@RequestMapping(value = "/getCustomer/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public Customer getCustomerById(@PathVariable int id) {
return customerService.getCustomer(id);

@RequestMapping(value = "/addCustomer", method = RequestMethod.POST, headers = "Accept=application/json")
public String addCustomer(@ModelAttribute("customer") Customer customer) {

return "redirect:/getAllCustomers";

@RequestMapping(value = "/updateCustomer/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public String updateCustomer(@PathVariable("id") int id,Model model) {
model.addAttribute("customer", this.customerService.getCustomer(id));
model.addAttribute("listOfCustomers", this.customerService.getAllCustomers());
return "customerDetails";

@RequestMapping(value = "/deleteCustomer/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public String deleteCustomer(@PathVariable("id") int id) {
return "redirect:/getAllCustomers";


Service Layer

Step 7: Create a file named “” in package .org.arpit.java2blog.service

package org.arpit.java2blog.service;

import java.util.List;

import javax.transaction.Transactional;

import org.arpit.java2blog.dao.CustomerDao;
import org.arpit.java2blog.springboot.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

public class CustomerService {

CustomerDao customerDao;

public List<Customer> getAllCustomers() {
return customerDao.getAllCustomers();

public Customer getCustomer(int id) {
return customerDao.getCustomer(id);

public void addCustomer(Customer customer) {

public void updateCustomer(Customer customer) {


public void deleteCustomer(int id) {

DAO layer

Step 8: Create a interface named “” in package .org.arpit.java2blog.dao

package org.arpit.java2blog.dao;

import java.util.List;

import org.arpit.java2blog.springboot.Customer;

public interface CustomerDao {
public List<Customer> getAllCustomers() ;

public Customer getCustomer(int id) ;

public Customer addCustomer(Customer customer);

public void updateCustomer(Customer customer) ;

public void deleteCustomer(int id) ;

Step 9: Create a file named “” in package .org.arpit.java2blog.dao

package org.arpit.java2blog.dao;

import java.util.List;

import org.arpit.java2blog.springboot.Customer;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

public class CustomerDaoImpl implements CustomerDao{

private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;

public List<Customer> getAllCustomers() {
Session session = this.sessionFactory.getCurrentSession();
List<Customer> customerList = session.createQuery("from Customer").list();
return customerList;

public Customer getCustomer(int id) {
Session session = this.sessionFactory.getCurrentSession();
Customer customer = (Customer) session.get(Customer.class, id);
return customer;

public Customer addCustomer(Customer customer) {
Session session = this.sessionFactory.getCurrentSession();;
return customer;

public void updateCustomer(Customer customer) {
Session session = this.sessionFactory.getCurrentSession();

public void deleteCustomer(int id) {
Session session = this.sessionFactory.getCurrentSession();
Customer p = (Customer) session.load(Customer.class, new Integer(id));
if (null != p) {


Step 10: Create a file named “customerDetails.jsp” in package /WEB-INF/

<%@ taglib uri="" prefix="c" %>
<%@ taglib uri="" prefix="spring" %>
<%@ taglib uri="" prefix="form" %>
background: #25A6E1;
filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#25A6E1',endColorstr='#188BC0',GradientType=0);
padding:3px 5px;
font-family:'Helvetica Neue',sans-serif;
border:1px solid #1A87B9
table {
font-family: "Helvetica Neue", Helvetica, sans-serif;
width: 50%;
th {
background: SteelBlue;
color: white;
border: 1px solid gray;
width: 25%;
text-align: left;
padding: 5px 10px;
<form:form method="post" modelAttribute="customer" action="${pageContext.request.contextPath}/addCustomer">
<th colspan="2">Add Customer</th>
<form:hidden path="id" />
<td><form:label path="customerName">Customer Name:</form:label></td>
<td><form:input path="customerName" size="30" maxlength="30"></form:input></td>
<td><form:label path="email">Email:</form:label></td>
<td><form:input path="email" size="30" maxlength="30"></form:input></td>
<td colspan="2"><input type="submit"
class="blue-button" /></td>
<h3>Customer List</h3>
<c:if test="${!empty listOfCustomers}">
<table class="tg">
<th width="80">Id</th>
<th width="120">Customer Name</th>
<th width="120">Email</th>
<th width="60">Edit</th>
<th width="60">Delete</th>
<c:forEach items="${listOfCustomers}" var="customer">
<td><a href="<c:url value='/updateCustomer/${}' />" >Edit</a></td>
<td><a href="<c:url value='/deleteCustomer/${}' />" >Delete</a></td>

Spring boot main file

Step 11: Create a file named “” in package .org.arpit.java2blog

package org.arpit.java2blog;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

public class SpringBootHibernateApplication {

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

We have just added @SpringBootApplication and it does all the work.
Let’s understand more about this annotation.
@SpringBootApplication is an annotation that adds all of the following:

@Configuration makes the class as a source of bean definitions for the application context.
@EnableAutoConfiguration enables Spring boot to add beans present in classpath setting and various property setting.
Normally you would add @EnableWebMvc for a Spring MVC application, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath.
This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.

@ComponentScan tells Spring to look for other components, configurations, and services in the default package, allowing it to find the controllers.
If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

Run the application

Step 12: It ‘s time to do maven build.

Right click on project -> Run as -> Maven build

Step 13: Provide goals as clean install spring-boot:run (given below) and click on run

Step 14: Once you are done with Maven build, let’s go to the browser and put following URL.


You will see below screen.
Add follow details to Customer Name : as “John” and email as “” and click on submit.
Now I am adding more customers using above method.
Let’s click on edit link corresponding to customer Id :3 whose name is David.
I am changing email address from “” to “”

When you click on submit, you will see below screen.
As you can see David’s email address got changed to “”.
Let’s click on delete link corresponding to customer id :2 whose name is Martin and you will see below screen.

As you can see, Martin got deleted from the list.
That’s all about Spring Boot Hibernate example.


Đăng nhận xét