Skip to content
Related Articles
Open in App
Not now

Related Articles

How to Create a Project using Spring MVC and Hibernate 5?

Improve Article
Save Article
Like Article
  • Last Updated : 31 Oct, 2022
Improve Article
Save Article
Like Article

Spring MVC is a popular model view controller framework that handles dependency injection at run time. Hibernate 5 is an ORM framework that acts as an abstraction over the database. It allows interaction with the underlying database by removing any implementation details which is handled by hibernate. In this article, we will integrate Spring MVC and Hibernate 5 with an in-memory database h2.


  • Maven 
  • IDE (Preferably IntelliJ)
  • Java 8+

Required Dependencies

After creating an empty project you will need some core dependencies which are required for a bootstrap setup. In the dependencies section of your pom.xml add the following dependencies


The spring-orm module provides integration with hibernate




Core hibernate module for the hibernate dependencies




In-memory database




commons dependency for connection pooling




helps generate boilerplate code for constructors/setters/getters etc




Hibernate requires certain configurations to bootstrap such as DB path, driver, username, password, etc. We are going to use the annotation-based configuration an XML-based configuration can also be used if needed. 

Create a file: file will contain the basic configurations of the database we will read this source to configure our hibernate session

# MySQL properties

# Hibernate properties

Configuring the Application

Create a configuration class to wire the details for hibernate and set up the session factory etc


import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
public class ExampleConfiguration {
    private Environment env;
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
                new String[]{"com.example"});
        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();
                "", env.getProperty(""));
                "hibernate.dialect", env.getProperty("hibernate.dialect"));
        return hibernateProperties;

Model class

model class for the entity/table


package example.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Table(name = "user")
public class User {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;

Repository class

The persistence layer to persist the model in the database


package example.repository;
import example.model.User;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
public class UserRepository {
    private SessionFactory sessionFactory;
    public void addUser(User user) {
    public User getUsers(int id) {
        return sessionFactory.getCurrentSession().get(User.class, id);

Service class

service class to interact with the repository and persist items


package example.service;
import example.model.User;
import example.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
public class UserService {
    private final UserRepository userRepository;
    public void addUser(User user) {
    public User getUser(int id) {
        return userRepository.getUsers(id);

Application class

This is the entry point of the application, we need to wire this configuration to the application context.


package example;
import example.model.User;
import example.service.UserService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ExampleApplication {
    public static void main(String[] args) {
        System.out.println("Starting application");
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(ExampleConfiguration.class);
        UserService userService = context.getBean(UserService.class);
        // add user to the repo
        userService.addUser(new User(1, "john", "doe"));
        // search for the user in the repo
        User user = userService.getUser(1);


Hibernate: drop table user if exists
Hibernate: create table user (id integer generated by default as identity, first_name varchar(255), last_name varchar(255), primary key (id))
Oct 17, 2022 3:44:14 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Hibernate: insert into user (id, first_name, last_name) values (null, ?, ?)
Hibernate: select as id1_0_0_, user0_.first_name as first_na2_0_0_, user0_.last_name as last_nam3_0_0_ from user user0_ where
User(id=1, firstName=john, lastName=doe)

Package Structure:

Package Structure


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!